【问题标题】:Reusing php class variable重用php类变量
【发布时间】:2016-05-19 17:06:43
【问题描述】:
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)

【问题讨论】:

    标签: php python class variables


    【解决方案1】:

    你不能像你声明的那样做$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
    

    【讨论】:

      猜你喜欢
      • 2013-04-24
      • 1970-01-01
      • 2020-12-20
      • 2011-09-10
      • 1970-01-01
      • 1970-01-01
      • 2016-09-15
      • 2014-01-03
      • 1970-01-01
      相关资源
      最近更新 更多