Reputation: 941
I yesterday discovered strange issue in my class - hope you know some answers. Consider such a class:
class Person {
public $height = 90;
public $weight = $this->height * 0.8;
}
This class returns an error "Parse error: syntax error, unexpected T_VARIABLE" and it seems i can not declare variable in class that is variable itself. Can I only set "static" values to variables in class (i mean static like directly declared like string or int no static like "static $var = 'xyz'";Why is that happening?
Thanks, Kalreg.
Upvotes: 1
Views: 39
Reputation: 7010
properties cannot have dynamic values in the class definition, but you can define the weight in the __construct method if you want:
class Person {
public $height = 90;
public $weight;
public function __construct()
{
$this->weight = $this->height * 0.8;
}
}
Upvotes: 0
Reputation: 37365
Currently, you can use only constant expressions when defining default properties values in PHP. That means you can not use anything that will be evaluated at run-time. Since $this
refers to dynamic instance value, it is run-time, obviously, and cannot be used in such definitions.
Upvotes: 5