php中单引号双引号那点事---顺便说说把php变量的值传给js
2016-02-22 21:29
676 查看
与C语言相比, php的语法真是太自由了, 在php中, 认为'good'和"good"是一个东东, 这让学C语言的人何以堪啊。
下面看看php的单双引号吧:
hello
good
hello good
hello $s
可见单引号没有将其中的变量做对应替换, 是这样吗? 且看:
hello
good
hello good
hello $s
hello 'good'
hello "$s"
可见, 是否做替换, 是由最外层的引号决定的。
我们看看str的用法, 这个非常重要, 在php吐出html代码时, 经常需要这么用, 比如:
<html><button onclick="func('1')">ok</button> <script>
function func(f)
{
alert(f);
}
</script></html>
把结果作为html代码来运行, 可以得到正确的结果, 弹框为1. 这样就把php变量的值传给js了。 当然, 也可以这么搞:
经测试, 结果也是OK的. 写成如下的也好玩啊:
下面看看php的单双引号吧:
<?php $s = "good"; $str1 = <<<EOT hello $s EOT; $str2 = "hello $s"; $str3 = 'hello $s'; print_r($str1); echo "\n"; print_r($str2); echo "\n"; print_r($str3); echo "\n"; ?>结果:
hello
good
hello good
hello $s
可见单引号没有将其中的变量做对应替换, 是这样吗? 且看:
<?php $s = "good"; $str1 = <<<EOT hello $s EOT; $str2 = "hello $s"; $str3 = 'hello $s'; $str4 = "hello '$s'"; $str5 = 'hello "$s"'; print_r($str1); echo "\n"; print_r($str2); echo "\n"; print_r($str3); echo "\n"; print_r($str4); echo "\n"; print_r($str5); echo "\n"; ?>结果为:
hello
good
hello good
hello $s
hello 'good'
hello "$s"
可见, 是否做替换, 是由最外层的引号决定的。
我们看看str的用法, 这个非常重要, 在php吐出html代码时, 经常需要这么用, 比如:
<?php $flag = 1; $html = "<html>"; $html .= "<button onclick=\"func('$flag')\">ok</button>"; $html .= <<<EOT <script> function func(f) { alert(f); } </script> EOT; $html .= "</html>"; print_r($html); ?>结果为:
<html><button onclick="func('1')">ok</button> <script>
function func(f)
{
alert(f);
}
</script></html>
把结果作为html代码来运行, 可以得到正确的结果, 弹框为1. 这样就把php变量的值传给js了。 当然, 也可以这么搞:
<?php $flag = 1; $html = <<<EOT <html> <button onclick="func('$flag')">ok</button> <script> function func(f) { alert(f); } </script> </html> EOT; print_r($html); ?>
经测试, 结果也是OK的. 写成如下的也好玩啊:
<?php $flag = "abc"; $html = <<<EOT <html> <button onclick="func('$flag')">ok</button> <script> function func(f) { alert(f); } </script> </html> EOT; print_r($html); ?>不多说。 实际上, 很多时候, 单引号可以直接去掉。
相关文章推荐
- 23.php使用注册表
- php函数不能直接访问外部变量
- 用php的定界符EOT需要留个心眼
- thinkphp_3.1.2介绍和安装
- php编译安装
- yii学习历程1——归档文件安装
- script_language.php
- getPath()与getAbsolutePath()
- PhpStorm 配置在浏览器中打开文件
- PHP初学之控制结构
- PHP初学之运算符
- 自定义ContentProvider
- 数据存储ContentProvider
- 关于CRTP(Curiously Recurring Template Prattern)的使用
- YII2
- ContentProvider应用组件实例记录
- RTP timestamp与帧率及时钟频率的关系
- php emoji表情处理
- php设置cookie,在js中如何获取
- 使用PHP+Sphinx建立高效的站内搜索引擎