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

Asked

Viewed 419 times

5

Normally I do so:

$a = new MinhaClass($Parametro);

You can do this without creating the variable $a ? Only with the new?

2 answers

7


Yes, it is, but it is not very useful because the object will die soon after since it did not want to store it. In some cases it may be enough, but if it is, you probably didn’t need to create 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 shouldn’t be a class. So my answer does not speak of this.

class MinhaClass {}
new MinhaClass($Parametro);

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

4

You can do it like this:

(new MyClass());

You can also run methods, for example:

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

And even use within functions, as in a echo:

echo (new Auth())->getToken();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.