我可以使用父类的方法创建子类的对象

时间:2015-05-13 22:07:19

标签: php

所以我有这个父类:

    class Table {

    protected static $table_name;
    protected static $tbl_columns=array();

    public static function instance($row_from_db){
        $object=new self;
        foreach (self::$tbl_columns as $key=>$property){
            $object->$property =    $row_from_db[$property];
        }
        return $object;
    }
 }

当我在类Table的某个子类中调用“instance”方法时,它生成类Table的对象而不是子类的对象。

使用此代码有什么办法吗?或者有关如何解决它的任何建议?感谢

1 个答案:

答案 0 :(得分:1)

由于PHP 5.3.0使用Late Static Bindings

$object = new static;
foreach (static::$tbl_columns as $key=>$property){

这也有效:

$class = get_called_class();
$object = new $class;
foreach ($class::$tbl_columns as $key=>$property){