Skip to content
Advertisement

PHP- difference between instantiating a class and returning the instantiation

The normal class declaration and instantiation:

class Foo {
    // properties
    // methods 
}

new Foo();

The class declaration and instantiation with return:

class FooBar {
    // properties
    // methods 
}

return new FooBar();

What is the difference between these two in PHP in terms of using the classes?

Advertisement

Answer

If you just return new FooBar() it will just execute its __construct method if it has. But you can call methods without assigning objects to a variable. Like this:

return (new FooBar())->yourMethod();
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement