为什么这些神奇的方法不起作用?
Why are these magical methods not working?
运行这段代码后的结果如下,有人能解释一下为什么名字没有正确传递,所以会说"Icefeet is years old"
我在这里遗漏了什么吗?
is years old
<?php
class Penguin {
public function __construct($name) {
$this->species = 'Penguin';
$this->name = $name;
}
public function __toString() {
return $this->name . " (" . $this->species . ")\n";
}
public function getPenguinFromDb($id) {
// elegant and robust database code goes here
}
public function __get($field) {
if($field == 'name') {
return $this->username;
}
}
public function __set($field, $value) {
if($field == 'name') {
$this->username = $value;
}
}
public function __call($method, $args) {
echo "unknown method " . $method;
return false;
}
}
$tux = new Penguin('Icyfeet');
echo $tux->created;
echo $tux->name . " is " . $tux->age . " years old\n";
?>
我认为您正在尝试访问用户名而不是名称。
public function __get($field) {
if($field == 'name') {
return $this->name;
}
}
那么,在此之前,请声明 class 的所有字段,例如:
私有 $name = '';
私有 $species= 'Penguin';
运行这段代码后的结果如下,有人能解释一下为什么名字没有正确传递,所以会说"Icefeet is years old" 我在这里遗漏了什么吗?
is years old
<?php
class Penguin {
public function __construct($name) {
$this->species = 'Penguin';
$this->name = $name;
}
public function __toString() {
return $this->name . " (" . $this->species . ")\n";
}
public function getPenguinFromDb($id) {
// elegant and robust database code goes here
}
public function __get($field) {
if($field == 'name') {
return $this->username;
}
}
public function __set($field, $value) {
if($field == 'name') {
$this->username = $value;
}
}
public function __call($method, $args) {
echo "unknown method " . $method;
return false;
}
}
$tux = new Penguin('Icyfeet');
echo $tux->created;
echo $tux->name . " is " . $tux->age . " years old\n";
?>
我认为您正在尝试访问用户名而不是名称。
public function __get($field) {
if($field == 'name') {
return $this->name;
}
}
那么,在此之前,请声明 class 的所有字段,例如:
私有 $name = ''; 私有 $species= 'Penguin';