是否可以在PHP中动态定义类属性值? [英] Is it possible to define a class property value dynamically in PHP?

查看:60
本文介绍了是否可以在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆