taesu taesu - 5 months ago 6x
PHP Question

Reusing php class variable

class Human{
private $name = 'Foobar';
private $nick_name = 'King Foobar';

I wish to write this like this;

class Human{
private $name = 'Foobar';
private $nick_name = 'King '.$this->name; // doesn't work, ignore the . error
private $nick_name = 'King '.$name; // doesn't work, ignore the . error

however, PHP complains. Is there a way for me to get around it?

I know it's possible in Python

class Human:
name = 'Foobar'
nick_name = 'King '+name

a = Human()


You can't do $this->name as you declare it because $this is not initialized yet.

However, you could do it in the constructor to achieve what you want.

class Human{
    private $name;
    private $nick_name;

    public function __construct(){
        $this->name = "Foobar";
        $this->nick_name = "King " . $this->name;

You could also add optional parameters to the constructor if you'd like...

public function __construct($name = "Foobar", $nickname = NULL){
    $this->name = $name;

    // If the nickname is null, it will be King and the name
    // Otherwise it will be the nickname passed in the parameter
    $this->nick_name = $nickname ? $nickname : ("King " . $this->name);

The result would be:

$humanA = new Human(); // Name: Foobar && Nickname: King Foobar
$humanB = new Human('MyName'); // Name: MyName && Nickname: King MyName
$humanC = new Human('MyName', 'MyNickname'); // Name: MyName && Nickname: MyNickname