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

I had never seen anything like it before.

$dbTable = new $dbTable(); 

Are we saving an instance of an object inside $ dbTable?

Will we convert a string to an object?

Here's the context:

 protected $_dbTable; public function setDbTable($dbTable) { if (is_string($dbTable)) { $dbTable = new $dbTable(); } if (!$dbTable instanceof Zend_Db_Table_Abstract) { throw new Exception('Invalid table data gateway provided'); } $this->_dbTable = $dbTable; return $this; } 

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

We can read:

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

But this is similar to the concatenation operation between a string and these "things" :() - without using a period. So I'm still not sure what is going on here.

+6
source share
3 answers

No, line:

 if (is_string($dbTable)) { 

Means that a new $dbTable will only be created if the input is a string. So what happens here is that $dbTable contains the name of the class created when this code was executed:

 $dbTable = new $dbTable(); 

Then, then the code checks to make sure that an object of the appropriate 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 specify does not even execute.

+7
source

I believe this does - it creates a new object from the class with the 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' 
+3
source

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

Thus, this allows you to call the method as follows:

 $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 accept a constructor argument.

The syntax $obj = new $className() allows you to create objects from classes defined at runtime.

+1
source

Source: https://habr.com/ru/post/887552/


All Articles