Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 575
Manu Avatar asked Aug 18 '11 14:08

Manu


2 Answers

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
like image 171
zzzzBov Avatar answered Oct 13 '22 12:10

zzzzBov


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.

like image 23
Drekembe Avatar answered Oct 13 '22 12:10

Drekembe