是否可以在PHP中动态定义类属性值


Is it possible to define a class property value dynamically in PHP?

是否可以定义PHP类属性并使用同一类中的属性动态分配值?像这样:

class user {
    public $firstname = "jing";
    public $lastname  = "ping";
    public $balance   = 10;
    public $newCredit = 5;
    public $fullname  = $this->firstname.' '.$this->lastname;
    public $totalBal  = $this->balance+$this->newCredit;
    function login() {
        //some method goes here!
    }
}

收益 率:

解析错误:语法错误,第 6 行意外的"$this"(T_VARIABLE

上面的代码有什么问题吗?如果是这样,请指导我,如果不可能,那么实现这一目标的好方法是什么?

你可以像这样把它放到构造函数中:

public function __construct() {
    $this->fullname  = $this->firstname.' '.$this->lastname;
    $this->totalBal  = $this->balance+$this->newCredit;
}

为什么你不能按照你想要的方式去做?手册中的一句话解释了它:

声明可能包含初始化,但此初始化必须是常量值,也就是说,它必须能够在编译时进行评估,并且不得依赖于运行时信息才能进行评估。

有关 OOP 属性的更多信息,请参阅手册:http://php.net/manual/en/language.oop5.properties.php

不,您不能设置这样的属性。

但是:您可以在构造函数中设置它们,因此如果有人创建类的实例,它们将可用:

public function __construct()
{
    $this->fullname = $this->firstname . ' ' . $this->lastname;
}