您不能像那样在类属性中设置动态值;它们必须是常数值。您必须在构造函数中进行此类分配
// NO
private $person_info = $this->getName . ' ' . $this->getGender . ' and ' . $this->getAge() . '.';
// YES
public function __construct() {
$this->person_info = $this->getName . ' ' . $this->getGender . ' and ' . $this->getAge() . '.';
}
但你真正的意思是这个
// you're calling get methods, not properties
// make sure to use $this->getName(), not $this->getName
public function __construct() {
$this->person_info = $this->getName() . ' ' . $this->getGender() . ' and ' . $this->getAge() . '.';
}
但实际上你所有的代码都是坏的
// This makes no sense to have as a constant property in a class
private $person = array(
'name' => 'Sarah',
'gender' => 'female',
'age' => 21
);
这个类对你的目的更有意义
class Person {
// container for your info object
private $info = [];
// make info a parameter for your constructor
public function __construct(array $info = []) {
$this->info = $info;
}
// use PHP magic method __get to fetch values from info array
public function __get(string $attr) {
return array_key_exists($attr, $this->info)
? $this->info[$attr]
: null;
}
// use PHP magic method __set to set values in the info array
public function __set(string $attr, $value) {
$this->info[$attr] = $value;
}
// single method to fetch the entire info object
public function getInfo() {
return $this->info;
}
}
简单。让我们看看它现在是如何工作的
$p = new Person([
'name' => 'Sarah',
'gender' => 'female',
'age' => 21
]);
echo $p->name, PHP_EOL;
// Sarah
echo $p->gender, PHP_EOL;
// female
echo $p->age, PHP_EOL;
// 21
echo json_encode($p->getInfo()), PHP_EOL;
// {"name":"Sarah","gender":"female","age":21}
因为$info数组现在是一个参数,你可以很容易地用其他数据创建Person对象
$q = new Person([
'name' => 'Joey',
'gender' => 'male',
'age' => 15
]);
echo $q->name, PHP_EOL;
// Joey
echo $q->gender, PHP_EOL;
// male
echo $q->age, PHP_EOL;
// 15
echo json_encode($q->getInfo()), PHP_EOL;
// {"name":"Joey","gender":"male","age":15}