phpvariableszend-certification

Can I declare a variable without $ in 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?


Solution

  • 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.