将函数的结果赋给PHP类中的变量?OOP古怪

Jay*_*Jay 3 php oop variables class function

我知道你可以将函数的返回值赋给变量并使用它,如下所示:

function standardModel()
{
    return "Higgs Boson";   
}

$nextBigThing = standardModel();

echo $nextBigThing;
Run Code Online (Sandbox Code Playgroud)

所以有人请告诉我为什么以下不起作用?或者它还没有实现?我错过了什么吗?

class standardModel
{
    private function nextBigThing()
    {
        return "Higgs Boson";   
    }

    public $nextBigThing = $this->nextBigThing();   
}

$standardModel = new standardModel;

echo $standardModel->nextBigThing; // get var, not the function directly
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样做:

class standardModel
{
    // Public instead of private
    public function nextBigThing()
    {
        return "Higgs Boson";   
    }
}

$standardModel = new standardModel;

echo $standardModel->nextBigThing(); // Call to the function itself
Run Code Online (Sandbox Code Playgroud)

但是在我的项目中,存储在类中的所有信息都是预定义的公共变量,除了其中一个,需要在运行时计算值.

我希望它一致,所以我或任何其他使用此项目的开发人员必须记住,一个值必须是函数调用而不是var调用.

但是不要担心我的项目,我主要想知道为什么PHP的解释器中的不一致?

显然,这些例子是为了简化事情而编写的.请不要质疑"为什么"我需要在课堂上放置所述功能.我不需要有关正确OOP的课程,这只是一个概念证明.谢谢!

dec*_*eze 7

public $nextBigThing = $this->nextBigThing();   
Run Code Online (Sandbox Code Playgroud)

您只能使用常量值初始化类成员.也就是说,此时你不能使用函数或任何表达式.此外,这个类在这一点上甚至没有完全加载,所以即使它被允许,你可能也无法在它仍然被构造时调用它自己的函数.

做这个:

class standardModel {

    public $nextBigThing = null;

    public function __construct() {
        $this->nextBigThing = $this->nextBigThing();
    }

    private function nextBigThing() {
        return "Higgs Boson";   
    }

}
Run Code Online (Sandbox Code Playgroud)


Jon*_*uhn 6

除非该值是恒定的数据类型(如字符串,整数...等)不能默认值分配给这样的性质.任何本质上处理代码(如功能,即使$ _SESSION值)不能被指定为默认值的属性.你可以做的是在构造函数中为属性分配你想要的任何值.

class test {
    private $test_priv_prop;

    public function __construct(){
        $this->test_priv_prop = $this->test_method();
    }

    public function test_method(){
        return "some value";
    }
}
Run Code Online (Sandbox Code Playgroud)