Cannot set variable in class equal to a function

送分小仙女□ 提交于 2019-12-24 12:25:39

问题


I started today with learning object oriented PHP programming and I am struggling with the following problem:

I can set a variable equal to for example 10:

class exampleClass {
   private $number = 10;
}

But I cannot set it equal to a function which returns 10:

class exampleClass {
   private $number = exampleFunction();
}

回答1:


You can't set class properties directly as expressions:

Invalid:

class Test {
    protected $blah = 1 + 1;
}

Instead set it in the class construct:

class Test {
    protected $blah;

    public function __construct() {
        $this->blah = 1 + 1;
    }
} 


来源:https://stackoverflow.com/questions/27019646/cannot-set-variable-in-class-equal-to-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!