gpt4 book ai didi

php - 重用 php 类变量

转载 作者:太空宇宙 更新时间:2023-11-04 08:02:43 26 4
gpt4 key购买 nike

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

关于php - 重用 php 类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37329829/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com