失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > php中单引号双引号那点事---顺便说说把php变量的值传给js

php中单引号双引号那点事---顺便说说把php变量的值传给js

时间:2018-07-16 21:57:04

相关推荐

php中单引号双引号那点事---顺便说说把php变量的值传给js

与C语言相比, php的语法真是太自由了, 在php中, 认为'good'和"good"是一个东东, 这让学C语言的人何以堪啊。

下面看看php的单双引号吧:

<?php$s = "good";$str1 = <<<EOThello$sEOT;$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 = <<<EOThello$sEOT;$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 οnclick="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);?>

不多说。实际上, 很多时候, 单引号可以直接去掉。

如果觉得《php中单引号双引号那点事---顺便说说把php变量的值传给js》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。