简体   繁体   中英

How can I create dynamically objects based on array values in php?

I'ld like to dynamically create as many object as present in my $instance array (eg domain1_com and domain2_com ) and give them the name of array value (eg domain1_com and domain2_com ) so I can access it through these names (eg domain1_com->example() ).

Is it possible? I tried something like this but obviously doesn't work.

    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();

You can use variable variables.

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

is the same as

$foo = new bar();

You cannot access the variables created inside getInstances outside of that method. They are local, not global.

Try this code:

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();

It will produce this output:

This is an instance

This is an instance

E_NOTICE : type 8 -- Undefined variable: domain1_com -- at line 32

E_ERROR : type 1 -- Call to a member function example() on a non-object -- at line 32

You need a way to access those variables. I'd use this:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM