Is it possible to instantiate a class without storing it in a variable?

5

I usually do this:

$a = new MinhaClass($Parametro);

Can you do this without creating the $a variable? Only with new ?

    
asked by anonymous 31.12.2017 / 15:39

2 answers

7

Yes, it does, but it does not have much use because the object will die next since it did not want to store it. In some cases that may be enough, but if it is, you probably should not have created the class.

For example, if you just need to instantiate the object, calling a method and doing nothing else is a typical case where it should not be a class. So my answer does not speak of this.

class MinhaClass {}
new MinhaClass($Parametro);

See running on ideone . And in Coding Ground . Also put it in GitHub for future reference .

    
31.12.2017 / 15:46
4

You can do this:

(new MyClass());

You can also execute methods, for example:

(new MyClass())->init();

And even use within functions, as in echo :

echo (new Auth())->getToken();
    
31.12.2017 / 17:45