我正在学习PHP,并试图创建一个具有几个protected属性的基本类。我可以使用“魔术”设置器来设置它们,但是不能打印name属性。我已经读过了,这似乎是基本的东西,但出于某种奇怪的原因,输出是"name“而不是我传递的实际字符串。代码如下:
class Animal{
protected $name;
protected $color;
protected $type;
public function __set($attr, $value){
switch ($attr){
case "name":
$this->name = $attr;
break;
case "color":
$this->color = $attr;
break;
case "type":
$this->type = $attr;
break;
default:
echo "attr not found in class";
}
printf ("set %s to %s <br>", $attr, $value);
}
public function __get($attr){
if(property_exists($this, $attr)){
return $this->$attr;
}
}
public function run(){
echo $this->name ." runs! <br>";
}
public function getName(){
return $this->name."<br>";
}
}
$animal1 = new Animal();
$animal1->name = "Animal_1";
$animal1->color = "black";
$animal1->type = "common";
echo $animal1->getName();
echo $animal1->run();
echo $animal1->name;这是输出:
set name to Animal_1
set color to black
set type to common
name
name runs!
name为什么我不能获取类的name属性,而只获取属性本身的名称呢?
发布于 2017-02-05 03:44:11
更改:
$this->name = $attr;至:
$this->name = $value;因为根据您的切换情况将$attr设置为"name“,我假设$value包含了您实际需要的内容。
同样的事情也适用于您的其余切换案例。
发布于 2017-02-05 03:47:11
您当前将该属性的值设置为其键:
$this->name = $attr;而应将该值设置为$value
$this->name = $value;这将防止可能发生的任何错误。
附言:我刚刚注意到已经有人发布了同样的解决方案。Woops :)
https://stackoverflow.com/questions/42044788
复制相似问题