gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:57:37 25 4
gpt4 key购买 nike

是否可以定义一个 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!
}
}

产量:

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

关于php - 是否可以在 PHP 中动态定义类属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28988260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com