Can I have a function as a variable inside a PHP class?
Is it possible to create a variable which runs a function and holds its return value when it's called? Like in the example below:
class Object{
public $var = $this->doSomething();
function doSomething(){
开发者_StackOverflow return "Something";
}
}
$object = new Object();
echo $object->$var;
Just because I get this error:
Parse error: syntax error, unexpected T_VARIABLE in test.php on line 2
You must initialize it in the constructor (if the value is not some 'compile-time' constant):
class Object {
public $var;
function __construct() {
$this->var = $this->doSomething();
}
function doSomething() {
return "Something";
}
}
精彩评论