您的位置:首页 > 编程语言 > PHP开发

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

2016-02-22 21:29 676 查看
        与C语言相比, php的语法真是太自由了, 在php中, 认为'good'和"good"是一个东东, 这让学C语言的人何以堪啊。 

        下面看看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);
?>
      不多说。  实际上, 很多时候, 单引号可以直接去掉。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: