可以在PHP中动态定义类属性值吗?
是否可以定义PHP类属性并使用同一类中的属性动态分配值?比如:可以在PHP中动态定义类属性值吗?,php,class,oop,Php,Class,Oop,是否可以定义PHP类属性并使用同一类中的属性动态分配值?比如: class user { public $firstname = "jing"; public $lastname = "ping"; public $balance = 10; public $newCredit = 5; public $fullname = $this->firstname.' '.$this->lastname; public $totalB
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_变量)
上面的代码有什么错误吗?如果是这样,请指导我,如果不可能,那么什么是实现这一点的好方法?您可以将其放入构造函数中,如下所示:
public function __construct() {
$this->fullname = $this->firstname.' '.$this->lastname;
$this->totalBal = $this->balance+$this->newCredit;
}
你为什么不能按你想要的方式做呢?手册中的一段引文解释了这一点:
此声明可能包括初始化,但此初始化必须是一个常量值——也就是说,它必须能够在编译时进行计算,并且不能依赖于运行时信息
有关OOP属性的更多信息,请参阅手册:否,您不能设置这样的属性 但是:您可以在构造函数中设置它们,以便在有人创建类的实例时可以使用它们:
public function __construct()
{
$this->fullname = $this->firstname . ' ' . $this->lastname;
}
@Yuvi在初始化时,在类定义中,它必须是一个可以在编译时计算的常量值;在构造函数或其他函数中,您可以指定您想要的内容。如果要访问子类中的动态属性,请执行以下操作:?你怎么称呼它?在这方面我面临着挑战。@andex只要不覆盖子类中的属性,就可以这样访问它:
$this->yourProperty