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?
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.
No, this is an error. Defining:
public var1="Test"; //String
Will give you:
Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE
For details, see http://codepad.org/meMrSmfA.
Variables in PHP are "represented by a dollar sign followed by the name of the variable". Although dollarless variables have been requested, I doubt whether they we ever see them enabled.
Point in short: your code is invalid.
In php variable are auto casting.whatever you want keep in a variable no need to declare it type . But one mandatory thing is that when you going to declare a Variable in php you must have to use "$" which one you missed .Book declaration is
public var1="Test"; //String
public var2=1.23; //Numericvalue
public var3=array(1,2,3);
its a wrong declaration Right is
public $var1="Test"; //String
public $var2=1.23; //Numericvalue
public $var3=array(1,2,3);
that's other wise every thing are fine . Thank you