3

What is the reason the following code works and generates the given result. Is it a special language construct that is just supported by PHP? If so, then which one? Or is it just a simple php-ism?

class Foo {};

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

var_dump($a); // class Foo#1 (0)
var_dump($b); // class Foo#2 (0)
7
  • 6
    It is mentioned in Manual that this is available since PHP 5.3 php.net/manual/en/… Commented Jun 26, 2019 at 13:47
  • 2
    ^ look at: Example #5 Creating new objects (in the above link) Commented Jun 26, 2019 at 13:48
  • 5
    Question is not about examples and where to see them, question is "why this works". Commented Jun 26, 2019 at 13:50
  • 1
    Five upvotes in 10 minutes? Wow. It seems this question is much better than I believed... Commented Jun 26, 2019 at 14:00
  • 2
    I think the "why" of some specific language feature is pretty off-topic for SO... Commented Jun 26, 2019 at 14:04

1 Answer 1

1

PHP allows you to create an object instance from a variable like this:

$a = 'Foo';
$b = new $a;

So when you use the new $a, PHP is checking if it's a string to make a new instance of the class, and if it's an object, it's going to retrieve the class name of the object instance and make a new instance from it.

If you try to do the same with a non-string or non-object variable:

$a = 1;
$b = new $a;

This will generate an error:

PHP Error: Class name must be a valid object or a string

PHP 5.3.0 introduced a couple of new ways to create instances of an object, which is an example of a scenario like you've provided:

class Test {}

$obj1 = new Test();
$obj2 = new $obj1;

For more information: Read Example #5 Creating new objects under https://www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.new

Sign up to request clarification or add additional context in comments.

3 Comments

Do you have a link to the RFC that has changed this? Why was it added to PHP? Why is it useful?
$b = new get_class($a); throws me a fatal error. I am sure there is some syntactical mistake. If I store the return in a variable, it runs fine.
@u_mulder are you sure you read more than a single line of this answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.