Is it possible to dynamically determine the value of a class property in PHP?

Is it possible to define a property of a PHP class and dynamically assign a value using the property inside the same class? Sort of:

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!
    }
}

Productivity:

Parse error: syntax error, unexpected '$ this' (T_VARIABLE) on line 6

Is there something wrong in the above code? If yes, please help me, and if this is not possible, then what is a good way to do this?

+4
source share
2 answers

You can put it in the constructor as follows:

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

Why can't you do it the way you want? A quote from the manual explains this:

, --that, .

. : http://php.net/manual/en/language.oop5.properties.php

+11

, .

: , , - :

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

All Articles