1

有一个bug说如果你使用fetch_object('classname')_构造。那么如何在调用__set方法之前实例化对象。

4

1 回答 1

1

这个 Bug/Feature 是一个有趣的 PHP 缺陷。在这样的情况下很方便:

class MyModel {

    public $id;
    public $column2;
    public $column3;

    public function __construct() {
        //work with prefilled properties from database here
    }
}

$model = $mysqli->query()->fetch_object('MyModel');

它甚至在这种情况下也有效:

class MyModel {

    public $data;

    public function __construct() {
        //work with $this->data here
    }

    public function __set($name, $value) {
        $this->data[$name] = $value;
    }
}

$model = $mysqli->query()->fetch_object('MyModel');

但在这种情况下它会咬你:

class MyModel {

    public $data;

    public function __construct($someOtherService) {
        $this->service = $someOtherService;
    }

    public function __set($name, $value) {
        $this->service->workWith($name, $value);
        $this->data[$name] = $value;
    }
}

$model = $mysqli->query()->fetch_object('MyModel');
于 2012-11-05T15:17:58.297 回答