PHP中的继承 - 创建子实例并调用父方法

时间:2013-09-19 22:51:22

标签: php class inheritance methods

我有这样的事情:

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()指的是上面的最后一行。我遗漏了哪一步才能正确继承?

2 个答案:

答案 0 :(得分: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;
    }

}

答案 1 :(得分: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;
    }

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