如何在php中基于数组值动态创建对象?

时间:2015-01-24 15:52:58

标签: php static instance

我想动态创建我的$ instance数组中存在的对象(例如domain1_comdomain2_com),并为它们指定数组值的名称(例如domain1_comdomain2_com)所以我可以通过这些名称访问它(例如domain1_com->example())。

有可能吗?我试过这样的事情,但显然不起作用。

    class myClass
    {
        public static function getInstances()
        {
            // I connect to the database and execute the query
            $sql = "SELECT * FROM my_table";    
            $core = Core::getInstance();
            $stmt = $core->dbh->prepare($sql);

            if ($stmt->execute()) {
                $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
            }

            // Read values in my array
            foreach ($results as $instance) {

                $obj = $instance["domain"]);
                // return 2 values: domain1_com and domain2_com

                $obj = new myClass();
            }
        }

        public function example()
        {
            echo "This is an instance";
        }
    }

    myClass::getInstances();

    $domain1_com->example();
    $domain2_com->example();

1 个答案:

答案 0 :(得分:2)

您可以使用变量变量。

$name = "foo";
$$name = new bar();

相同
$foo = new bar();

您无法访问在该方法之外的getInstances内创建的变量。它们是本地的,而不是全球性的。

试试这段代码:

class myClass
{
    public static function getInstances()
    {
        $results = array('domain1_com', 'domain2_com');

        foreach ($results as $instance) {
            $$instance = new myClass();
            // This is equivalent to "$domainX_com = new myClass();".
            // Writing that code here would define a _local_ variable named 'domainX_com'.
            // This being a method inside a class any variables you define in here are _local_,
            // so you can't access them' _outside_ of this method ('getInstances')
        }

        // this will work, we are inside 'getInstances'
        $domain1_com->example();
        $domain2_com->example();
    }

    public function example()
    {
        echo "This is an instance";
    }
}

myClass::getInstances();

// this won't work. $domainX_com are not accessible here. they only exist _inside_ 'getInstances'
// It's basic OOP.
// so this code will crash
$domain1_com->example();
$domain2_com->example();

它将产生此输出:

  

这是一个实例

     

这是一个实例

     

E_NOTICE:输入8 - 未定义变量:domain1_com - 第32行

     

E_ERROR:类型1 - 在非对象上调用成员函数example() - 第32行

您需要一种方法来访问这些变量。我用这个:

class myClass
{
    private static $instances = array();
    public static function getInstances()
    {
        $results = array('domain1_com', 'domain2_com');

        foreach ($results as $instanceName) {
            self::$instances[$instanceName] = new myClass();
        }
    }

    public static function getInstance($instanceName) {
        return self::$instances[$instanceName];
    }

    public function example()
    {
        echo "This is an instance";
    }
}

myClass::getInstances();

// this will work
myClass::getInstance('domain1_com')->example();
myClass::getInstance('domain2_com')->example();