new $ this-> table()与new tablename();动态类生成

时间:2017-05-13 22:59:27

标签: php

我有以下课程:

namespace database;

class database {
    protected $table = '';

    function __construct()
    { // Stuff here }

    public function all() {
        // Load from database
        // Return array with results
    }
}

class tbl_organisation_types extends database {
    protected $table = 'tbl_organisation_types';

    function __construct($data = [])
    {
        parent::__construct();
        // do stuff with $data
    }
}

我从数据库中获取所有行,遍历它们并创建新对象。由于其他类扩展了此database类,因此生成的对象必须是动态的。

当我尝试像这样动态生成对象时

$return[] = new $this->table($row);

我收到以下错误

  

未捕获错误:类' tbl_organisation_types'在/path/to/tbl_organisation_types.php

中找不到

如果我生成具有固定类名的对象,则它可以正常工作。但是它不会适用于多个班级。

$return[] = new tbl_organisation_types($row);

有没有办法动态生成对象和/或为什么我的工作不起作用?

使用PHP 7.1

1 个答案:

答案 0 :(得分:0)

我得到的印象是,您正试图在那里创建类似active record的内容。我会反对这一点。

至于为什么你的班级没有工作,你可能会做类似的事情:

$name = '\\database\\' . $this->table; 
$instance = new $name($row);

当您使用字符串初始化类时,无论您的代码在哪个命名空间中,它都必须包含完全限定的类名。同样适用于别名。