当前位置: 移动技术网 > IT编程>开发语言>PHP > php 中 define 定义常量和单双引号问题

php 中 define 定义常量和单双引号问题

2018年11月01日  | 移动技术网IT编程  | 我要评论
一、define定义常量问题

      

<?php  

define('database', 'mysql');  

define('database_user', 'root');  

define('database_password', 'password');  

?>

 

             直接使用"database"常量,代表的就是"mysql"。

 

             $arr = array('fruit'=>'apple','veggie'=>'carrot');

 

             define('fruit','veggie');

             

             print $arr['fruit'];   //  apple

             print $arr[fruit];  //  carrot  

            * 注意 :[] 中没有引号。php会自动把key值当作常量来解析,然后去内存中找对应的常量,于是找到了fruit,然后解析key值。然后再去内存中找常量,没找到veggie,然后就把veggie当作真正的key值,找到对应的值。





               

二、单双引号问题

 

    error_reporting(e_all);

     $arr = array('fruit'=>'apple','veggie'=>'carrot');

 

    define('fruit','veggie');

    print $arr['fruit']; echo '<br/>';    //apple

    print $arr[fruit]; echo '<br/>';    //carrot

    print "hello $arr[fruit]"; echo '<br/>';  // apple

    print "hello {$arr[fruit]}"; echo '<br/>'; // hello carrot

    print "hello {$arr['fruit']}";  echo '<br/>';// hello apple

   //print "hello $arr['fruit']"; // 有错误

   //print "hello $_get['foo']"; // 有错误

   print "hello " . $arr['fruit']; // hello apple

 

注意: 数组方括号中如果没有加引号,php会首先按照常量来解析。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网