Another PHP Oddity: Calling new Against a Class Instance

A friend showed me this puzzling code the other day.

Can you guess the output?

Terminal
1
2
3
4
5
6
7
8
9
10
11
[22:11:41 mburke]$ php -a
Interactive shell

php > class Test { };
php > $A = new Test();
php > var_dump($A);
object(Test)#1 (0) {
}

php > $B = new $A();
php > var_dump($B);

If you guessed PHP Fatal error: Function name must be a string you would be wrong. PHP seldom does what you would expect.

Nope, its:

Terminal
1
2
object(Test)#2 (0) {
}

I’m having a hard time imagining a situation where this behavior could be useful. I suppose it gives you a brand new default instance of an unknown class. Unless of course the constructor had required parameters. Then who knows what comes out of it!

PHP is not a sane language.