Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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($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 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.

like image 710
MEM Avatar asked May 08 '11 12:05

MEM


People also ask

What is foo foo slang for?

Definition of foo-foo (Entry 1 of 2) slang. : fool, ninny.

What is Foooo?

Expression of disappointment or disgust. Oh foo - the cake burnt!

What does it mean when a guy calls you foo?

What Does Foo Mean? This slang term is an abbreviated form of the word “fool.” It is used to call someone foolish or gullible. It means that someone easily falls for something or is taken advantage of in many situations.

Where did the term foo come from?

The nonsense word "foo" emerged in popular culture during the early 1930s, first being used by cartoonist Bill Holman, who peppered his Smokey Stover fireman cartoon strips with "foo" signs and puns. The term "foo" was borrowed from Smokey Stover by a radar operator in the 415th Night Fighter Squadron, Donald J.


1 Answers

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.

like image 72
Justin Ethier Avatar answered Oct 11 '22 17:10

Justin Ethier