Skip to main content
 首页 » 编程设计

php之重用 php 类变量

2025年05月04日25lyhabc

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) 

请您参考如下方法:

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