开发者

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";
     }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜