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

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

是否可以定义 PHP class 属性 并在同一个 class 中使用 属性 动态分配值?类似于:

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!
    }
}

产量:

Parse error: syntax error, unexpected '$this' (T_VARIABLE) on line 6

上面的代码有什么问题吗?如果是这样,请指导我,如果不可能,那么完成此任务的好方法是什么?

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

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

为什么你不能按照你想要的方式去做?手册中的引述对此进行了解释:

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

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

不,您不能那样设置属性。

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

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