为什么这些神奇的方法不起作用


Why are these magical methods not working?

运行此代码后的结果如下,有人能解释为什么名称没有正确传递,以至于它会说"Icefoots 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;
    }
  }

好吧,在此之前,请声明类的所有字段,如:

private$名称=";private$species="企鹅";