开发者

What does this mean: $foo = new $foo();?

开发者 https://www.devze.com 2023-03-03 13:47 出处:网络
I\'ve never seen something like this before. $dbTable = new $dbTable(); We are storing an Object Instance inside $dbTable ?

I've never seen something like this before.

$dbTable = new $dbTable();

We are storing an Object Instance inside $dbTable ?

Are we transforming a string into an object ?

Here's the context:

protected $_dbTable;

    public function setDbTable($dbTable)
    {
        if (is_string($dbT开发者_开发技巧able)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

From php manual here: http://www.php.net/manual/en/language.oop5.basic.php

We can read:

If a string containing the name of a class is used with new, a new instance of that class will be created. If the class is in a namespace, its fully qualified name must be used when doing this.

But this seems to be a concatenation operation between a string and those "things": () - without using a dot. So I'm still not sure about what's going on here.


No, the line:

if (is_string($dbTable)) {

Means that a new $dbTable will only be instantiated if the input is a string. So what is going on here is that $dbTable contains the name of a class that is created when that code executes:

$dbTable = new $dbTable();

And then later on the code checks to make sure an object of the proper type (Zend_Db_Table_Abstract) is created. As Stefan points out, an instance of the class can be passed directly, in which case the code you mentioned is not even executed.


I believe, that what this does – it creates new object from class with name stored in $dbTable

<?php

class MyClass {
    private $foo = 4;

    public function bar(){
        echo $this->foo;
    }
}

class MyClass2 {
    private $foo = 6;

    public function bar(){
        echo $this->foo;
    }
}

$a = 'MyClass';
$b = new $a();
$b->bar(); //echo '4'

$a = 'MyClass2';
$b = new $a();
$b->bar(); //echo '6'


The method either takes an instance of Zend_Db_Table_Abstract (or a subclass) as an argument or it takes a string argument with the name of the class to instantiate.

So essentially this allows you to call the method like this:

$dbTable = new My_Zend_Db_Table_Class();
$xy->setDbTable($dbTable);

// or

$dbTable = 'My_Zend_Db_Table_Class';
$xy->setDbTable($dbTable);

The latter only works if your custom class does not take any constructor argument.

The $obj = new $className() syntax allows you to instantiate objects from classes that are determined at runtime.

0

精彩评论

暂无评论...
验证码 换一张
取 消