关键词搜索

源码搜索 ×
×

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

发布2016-02-22浏览10408次

详情内容

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

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

 

  1. <?php
  2. $s = "good";
  3. $str1 = <<<EOT
  4. hello
  5. $s
  6. EOT;
  7. $str2 = "hello $s";
  8. $str3 = 'hello $s';
  9. print_r($str1);
  10. echo "\n";
  11. print_r($str2);
  12. echo "\n";
  13. print_r($str3);
  14. echo "\n";
  15. ?>

       结果:

 

    hello
    good
hello good
hello $s

       可见单引号没有将其中的变量做对应替换,  是这样吗? 且看:

 

  1. <?php
  2. $s = "good";
  3. $str1 = <<<EOT
  4. hello
  5. $s
  6. EOT;
  7. $str2 = "hello $s";
  8. $str3 = 'hello $s';
  9. $str4 = "hello '$s'";
  10. $str5 = 'hello "$s"';
  11. print_r($str1);
  12. echo "\n";
  13. print_r($str2);
  14. echo "\n";
  15. print_r($str3);
  16. echo "\n";
  17. print_r($str4);
  18. echo "\n";
  19. print_r($str5);
  20. echo "\n";
  21. ?>

      结果为:

 

    hello
    good
hello good
hello $s
hello 'good'
hello "$s"

      可见, 是否做替换, 是由最外层的引号决定的。

 

      我们看看str的用法, 这个非常重要, 在php吐出html代码时, 经常需要这么用, 比如:

 

  1. <?php
  2. $flag = 1;
  3. $html = "<html>";
  4. $html .= "<button onclick=\"func('$flag')\">ok</button>";
  5. $html .= <<<EOT
  6. <script>
  7. function func(f)
  8. {
  9. alert(f);
  10. }
  11. </script>
  12. EOT;
  13. $html .= "</html>";
  14. print_r($html);
  15. ?>

      结果为:

 

<html><button οnclick="func('1')">ok</button>    <script>
        function func(f)
        {
            alert(f);
        }
    </script></html>

 

       把结果作为html代码来运行, 可以得到正确的结果, 弹框为1.  这样就把php变量的值传给js了。 当然, 也可以这么搞:

 

  1. <?php
  2. $flag = 1;
  3. $html = <<<EOT
  4. <html>
  5. <button onclick="func('$flag')">ok</button>
  6. <script>
  7. function func(f)
  8. {
  9. alert(f);
  10. }
  11. </script>
  12. </html>
  13. EOT;
  14. print_r($html);
  15. ?>

       经测试, 结果也是OK的.  写成如下的也好玩啊:

 

  1. <?php
  2. $flag = "abc";
  3. $html = <<<EOT
  4. <html>
  5. <button onclick="func('$flag')">ok</button>
  6. <script>
  7. function func(f)
  8. {
  9. alert(f);
  10. }
  11. </script>
  12. </html>
  13. EOT;
  14. print_r($html);
  15. ?>

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

 

 

 

 

 

相关技术文章

最新源码

下载排行榜

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载