Manu
Manu

Reputation: 599

what does $a = new $b() mean in PHP?

Although I get it that

$a = new b()

would be initializing an object for the class b, but what would

$a = new $b()

mean because I came across some code that happens to work otherwise!

Upvotes: 6

Views: 436

Answers (2)

zzzzBov
zzzzBov

Reputation: 179166

It's a reflexive reference to the class with a name that matches the value of $b.

Example:

$foo = "Bar";

class Bar
{
   ...code...
}

$baz = new $foo();

//$baz is a new Bar

Update just to support: you can call functions this way too:

function test(){
    echo 123;
}
$a = "test";
$a(); //123 printed

Upvotes: 6

Drekembe
Drekembe

Reputation: 2716

This code:

$b = "Foo";
$a = new $b();

is equivalent to the following:

$a = new Foo();

Meaning that you can use syntax like $b() to dynamically refer to a function name or a class name.

Upvotes: 1

Related Questions