将函数的结果分配给PHP类中的变量? OOP怪异 [英] Assigning a function's result to a variable within a PHP class? OOP Weirdness

查看:93
本文介绍了将函数的结果分配给PHP类中的变量? OOP怪异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know you can assign a function's return value to a variable and use it, like this:

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

$nextBigThing = standardModel();

echo $nextBigThing;

所以有人请告诉我为什么下面的不工作?还是它还没有实现?我缺少一些东西?

So someone please tell me why the following doesn't work? Or is it just not implemented yet? Am I missing something?

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

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

$standardModel = new standardModel;

echo $standardModel->nextBigThing; // get var, not the function directly

我知道我可以这个:

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

$standardModel = new standardModel;

echo $standardModel->nextBigThing(); // Call to the function itself

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

But in my project's case, all of the information stored in the class are predefined public vars, except one of them, which needs to compute the value at runtime.

开发人员使用这个项目必须记住一个值必须是函数调用,而不是一个var调用。

I want it consistent so I nor any other developer using this project has to remember that one value has to be function call rather then a var call.

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

But don't worry about my project, I'm mainly just wondering why the inconsistency within PHP's interpreter?

显然,这些例子是为了简化。请不要问为什么我需要把该功能放在类中。我不需要一个正确的OOP课程,这只是一个概念的证明。感谢!

推荐答案

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

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

You can only initialize class members with constant values. I.e. you can't use functions or any sort of expression at this point. Furthermore, the class isn't even fully loaded at this point, so even if it was allowed you probably couldn't call its own functions on itself while it's still being constructed.

执行以下操作:

class standardModel {

    public $nextBigThing = null;

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

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

}

这篇关于将函数的结果分配给PHP类中的变量? OOP怪异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆