简体   繁体   English

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

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

Is it possible to define a PHP class property and assign the value dynamically using a property within the same class?是否可以定义 PHP 类属性并使用同一类中的属性动态分配值? 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!
    }
}

Yields:产量:

Parse error: syntax error, unexpected '$this' (T_VARIABLE) on line 6解析错误:语法错误,第 6 行出现意外的“$this”(T_VARIABLE)

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.这个声明可能包括一个初始化,但这个初始化必须是一个常量值——也就是说,它必须能够在编译时被评估,并且必须不依赖于运行时信息才能被评估。

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

No, you cannot set properties like that.不,您不能设置这样的属性。

However: you can set them in the constructor, so they will be available if someone creates an instance of the class :但是:您可以在构造函数中设置它们,因此如果有人创建类的实例,它们将可用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM