重用php类变量

时间:2016-05-19 17:06:43

标签: php python class variables

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

我希望这样写;

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
}
然而,PHP抱怨。我有办法解决它吗? 我知道这在Python中是可能的

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

a = Human()
print(a.nick_name)

1 个答案:

答案 0 :(得分:6)

由于$this->name尚未初始化,因此您无法宣布$this

但是,您可以在构造函数中执行此操作以实现所需。

class Human{
    private $name;
    private $nick_name;

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

如果您愿意,还可以向构造函数中添加可选参数。

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);
}

结果将是:

$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