3

我有这样的事情:

class MyParent {
    protected static $object;
    protected static $db_fields;

    public function delete() {
           // delete stuff
    }


    public static function find_by_id($id = 0) {
        global $database;
        $result_array = self::find_by_sql("SELECT * FROM " . static::$table_name . " WHERE id=" . $database -> escape_value($id) . " LIMIT 1");
        return !empty($result_array) ? array_shift($result_array) : false;
    }

     public static function find_by_sql($sql = "") {
        global $database;

        // Do Query
        $result_set = $database -> query($sql);

        // Get Results
        $object_array = array();
        while ($row = $database -> fetch_array($result_set)) {
            $object_array[] = self::instantiate($row);
        }

        return $object_array;
    }

   private static function instantiate($record) {
        $object = self::$object;
        foreach ($record as $attribute => $value) {
            if (self::has_attribute($attribute)) {
                $object -> $attribute = $value;
            }
        }
        return $object;
    }


}


class TheChild extends MyParent {

    protected static $db_fields = array('id', 'name');
    protected static $table_name = "my_table";

    function __construct() {
        self::$object = new TheChild;
    }

}

$child= TheChild::find_by_id($_GET['id']);
$child->delete();

我明白了: Call to undefined method stdClass::delete()参考上面的最后一行。我错过了正确继承的哪一步?

4

2 回答 2

2

你从来没有真正实例化这个TheChild类,这应该由

$var = new TheChild();

除了TheChild构造函数本身。

因此,静态 $object 字段永远不会受到影响(至少在您的示例中),因此影响它的字段(行$object -> $attribute = $value;)会导致创建 stdClass 对象,如此交互式 PHP shell 会话中所示:

php > class Z { public static $object; }
php > Z::$object->toto = 5;
PHP Warning:  Creating default object from empty value in php shell code on line 1
php > var_dump(Z::$object);
object(stdClass)#1 (1) {
  ["toto"]=>
  int(5)
}

该对象没有delete方法。

如前所述,实际创建TheChild实例将导致无限递归。

你想要做的是这样的,可能是:

class TheChild extends MyParent {

    protected static $db_fields = array('id', 'name');
    protected static $table_name = "my_table";

    function __construct() {
        self::$object = $this;
    }

}
于 2013-09-19T23:19:27.443 回答
1

编辑:您更新的代码显示了一个完整的不同示例:

class MyParent {
    protected static $object;

    public function delete() {
           // delete stuff
    }
}


class TheChild extends MyParent {

    function __construct() {
        self::$object = new TheChild;
    }


}

$child = new TheChild;
$child->delete();

从“Child's”构造函数中调用“Child's”构造函数将导致无限循环:

 function __construct() {
        self::$object = new TheChild; // will trigger __construct on the child, which in turn will create a new child, and so on.
    }

也许-我不知道您要达到什么目标-您正在寻找:

 function __construct() {
        self::$object = new MyParent;
    }

请注意,::Notation 不仅仅是一个不同的版本->- 它是完全不同的。一种是静态访问,另一种是对实际对象实例的访问!

于 2013-09-19T22:57:23.003 回答