简体   繁体   English

重用php类变量

[英]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. 但是,PHP抱怨。 Is there a way for me to get around it? 我有办法解决它吗?
I know it's possible in Python 我知道在Python中有可能

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

a = Human()
print(a.nick_name)

You can't do $this->name as you declare it because $this is not initialized yet. 您不能像声明那样使用$this->name ,因为$this尚未初始化。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM