douzhongjiu2263 2011-11-28 12:08
浏览 82
已采纳

我可以在PHP中声明一个没有$的变量

I saw this code in a PHP book (PHP architect, ZEND PHP 5 Certification guide page 141)

class foo{
  public $bar;
  protected $baz;
  private $bas;

  public var1="Test"; //String
  public var2=1.23; //Numericvalue
  public var3=array(1,2,3);
}

and it says

Properties are declared in PHP using one of the PPP operators, followed by their name:

Note that, like a normal variable, a class property can be initialized while it is being declared. However, the initialization is limited to assigning values (but not by evaluating expressions). You can’t,for example,initialize a variable by calling a function—that’s something you can only do within one of the class’ methods (typically, the constructor).

I can not understand how var1, var2, var3 are declared. Isn't it illegal?

  • 写回答

4条回答 默认 最新

  • dongsi3826 2011-11-28 12:16
    关注

    The sample code is (almost) valid (it's just missing a few $ signs.)

    class foo
    {
        // these will default to null
        public $bar;
        protected $baz;
        private $bas;
    
        // perfectly valid initializer to "string" value
        public $var1 = "Test"; //String
    
        // perfectly valid initializer to "float" value
        public $var2 = 1.23;    //Numericvalue
    
        // perfectly valid initializer to "array" value
        // (array() is a language construct/literal, not a function)
        public $var3 = array(1,2,3);
    }
    

    So, the book your code comes from is definitely in error.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Pwm双极模式H桥驱动控制电机
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题