Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
108 views
in Technique[技术] by (71.8m points)

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? 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

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...