0

Bellow 是一个 PHP 脚本。

我试图实现观察者模式(没有 MVC 结构)......只是基本的。

遇到的错误已在注释中指定。首先,我尝试将 User 对象添加到 UsersLibrary 存储库。出现诸如 User::update() 不存在之类的错误。

为什么会遇到这个错误?应该应用什么修复以及如何应用?

   interface IObserver {
       public function update(IObservable $sender);
   }
   interface IObservable   {
       public function addObserver(IObserver $obj);
       public function notify();
   }
   class UsersLibrary implements IObservable {
        private $container;
        private $contor;
    //private $z;
    public function __construct() {//IObserver $a)   {
        $this->container = array();
        $this->contor = 0;
        echo "<div>[constructing UsersLibrary...]</div>";
        $this->addObserver(new Logger());
        //$this->z = $a;
    }
    public function add($obj)  {
        echo "<div>[adding a new user...]</div>";
        $this->container[$this->contor] = $obj;
        $this->contor++;
        $this->notify();
    }
    public function get($index) {
        return $this->container[$index];
    }
    public function addObserver(IObserver $obj) {
        $this->container[] = $obj;
    }
    public function notify()    {
        echo "<div>[notification in progress...]</div>";
        foreach($this->container as $temp) {
            //echo $temp;
            #################################################################
            $temp->update(); //--------ERROR
        //Fatal Error: Call to a member function update() on a non-object.
            #################################################################
        }
        //$this->container[0]->update();
        //$this->z->update($this);
    }
}
class User   {
    private $id;
    private $name;
    public function __construct($id, $name) {
        $this->id = $id;
        $this->name = $name;
    }
    public function getId() {
        return $this->id;
    }
    public function getName()   {
        return $this->name;
    }
}
class Logger implements IObserver   {
    public function __construct()   {
        echo "<div>[constructing Logger...]</div>";
    }
    public function update(IObservable $sender) {
        echo "<div>A new user has been added.</div>";
    }
}
$a = new UsersLibrary(); //new Logger());
//$a->add(new User(1, "DemoUser1"));
//$a->add(new User(2, "DemoUser2"));
$a->add("Demo");
echo $a->get(0);
//echo $a->get(0)->getName();
4

2 回答 2

1

您的User类没有实现interface IObserver,因此没有强制使用该方法update()

您必须实例化 anew User()才能将其添加到UsersLibrary

$library = new UsersLibrary();
$user = new User(1, "Demo");
$library->add($user);

此外,您正在将用户和记录器混合到您的UsersLibrary容器中。也许考虑为他们分离容器?

于 2012-07-12T21:24:51.047 回答
0

您在$a->add()调用中传递的是字符串而不是对象。您应该传入一个对象,或者更改 UserLibrary::add() 中的代码以将其参数包装在适当的对象中(或者对其进行对象查找以看到一个字符串,例如查找具有该名称的用户)。

$user = new User(1, "Demo");
$a = new UsersLibrary();
$a->add($user);
于 2012-07-12T21:11:03.733 回答