是否可以在 PHP 中动态定义类属性值? [英] Is it possible to define a class property value dynamically in PHP?
问题描述
是否可以定义 PHP 类属性并使用同一类中的属性动态分配值?类似的东西:
Is it possible to define a PHP class property and assign the value dynamically using a property within the same class? Something like:
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)
Parse error: syntax error, unexpected '$this' (T_VARIABLE) on line 6
上面的代码有什么问题吗?如果是这样,请指导我,如果不可能,那么有什么好方法可以做到这一点?
Is anything wrong in the above code? If so, please guide me and if it is not possible then what is a good way to accomplish this?
推荐答案
你可以像这样把它放到构造函数中:
You can put it into the constructor like this:
public function __construct() {
$this->fullname = $this->firstname.' '.$this->lastname;
$this->totalBal = $this->balance+$this->newCredit;
}
为什么你不能按照你想要的方式做呢?手册中的引述解释了这一点:
Why can't you do it the way you wanted? A quote from the manual explains it:
这个声明可能包括一个初始化,但是这个初始化必须是一个常数值——也就是说,它必须能够在编译时被评估并且不能依赖于运行——时间信息以便进行评估.
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
For more infromation about OOP properties see the manual: http://php.net/manual/en/language.oop5.properties.php
这篇关于是否可以在 PHP 中动态定义类属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!