动态实例化包含在数组中的PHP类

时间:2016-06-01 12:51:51

标签: php

我正在尝试在数组中实例化一些类。这就是场景:我有很多类,例如:

class Class0 extends NumberedClasses{...}
class Class1 extends NumberedClasses{...}
class Class2 extends NumberedClasses{...}

它们会随着时间的推移而增加,所以不要以这种方式实例化它们:

$instances0 = new Class0();
$instances1 = new Class1();
$instances2 = new Class2();

我想要一个getter方法,就像这个:

function getStrategies(){
   return array(Class0, Class1, Class2);
}

所以我将来可以在该数组中添加类,并以这种方式调用它:

$strategies = $this->getStrategies();
for ($strategies as $strategy) { 
    $instance = new $strategy();
}

我习惯用js做类似的事情,我有窗口对象,所以我甚至可以用字符串实例化类(新窗口[“Class1”])。但我是PHP的新手,无法找到方法。

提前致谢,

1 个答案:

答案 0 :(得分:0)

可能会建议使用中介类来管理这些实例将是非常理想的。考虑一下:

SELECT  st.Id,
        COUNT(DISTINCT sy.Id) AS SystemCount,
        COUNT(DISTINCT pr.Id) AS ProductCount,
        CASE WHEN COUNT(DISTINCT sy.Id) = 0 THEN 0
             ELSE 1.0 * COUNT(DISTINCT pr.Id) / COUNT(DISTINCT sy.Id)
        END AS Average
FROM    Store AS st
LEFT JOIN Customer AS cu ON cu.DealerId = st.Id
LEFT JOIN System AS sy ON sy.CustomerId = cu.Id
LEFT JOIN Product AS pr ON pr.SystemId = sy.Id
GROUP BY st.Id;

现在;使用Class InstanceHelper,您可以轻松管理您的实例...甚至添加实例,删除实例等等....再次考虑这些测试:

    <?php

        class NumberedClasses{}
        class Class0 extends NumberedClasses{}
        class Class1 extends NumberedClasses{}
        class Class2 extends NumberedClasses{}


        class InstanceHelper {

            /**
             * @var array
             */
            protected $instances = array();

            public function addInstance($instanceKey, $instance) {
                if(!array_key_exists($instanceKey, $this->instances)){
                    $this->instances[$instanceKey] = $instance ;
                }
            }

            public function addInstances(array $arrayOfInstances) {
                foreach($arrayOfInstances as $instanceKey=>$instance){
                    if(!array_key_exists($instanceKey, $this->instances)){
                        $this->instances[$instanceKey] = $instance ;
                    }
                }
            }

            public function removeInstance($instanceKey) {
                if(array_key_exists($instanceKey, $this->instances)){
                    unset($this->instances[$instanceKey]);
                }
                return $this->instances;
            }

            public function getAllInstances() {
                return $this->instances;
            }
        }

以下是var_dumps的结果:

    <?php

        $insHelper          = new InstanceHelper();
        $instances          = array(
            'c0'    =>  new Class0(),
            'c1'    =>  new Class1(),
            'c2'    =>  new Class2(),
        );

        $insHelper->addInstances($instances);

        var_dump($insHelper->getAllInstances());
        var_dump($insHelper->removeInstance('c1'));