Using a PHP class without instantiating it in a variable is the same as calling a function?

1

Declare the class this way without instantiating it in a variable:

new ExampleNameClass( 'arg1', 'arg2' );

Would it be the same as using a function ?

ExampleFunction('arg1', 'arg2');

Since I did not store a variable, the class executes the construct at the time of the call and then dies ... In my view, this would be the identical behavior of a simple function in PHP. Am I wrong?

So the advantage of class compared to function , would be to run methods .

And in the function would not it?

( new ExampleNameClass('arg1', 'arg2') )->init();
    
asked by anonymous 16.07.2018 / 06:02

1 answer

4

It's not the same thing, and in fact it usually does not make much sense.

In fact methods are functions that work with a specific object. Since the constructor is a special function that creates this object. It may eventually do something other than initialize the object, but it is not usually recommended more than this.

In PHP I question the use of classes in general. But especially if it is a class that will not even have been, that is, an object itself. If it will not have multiple behaviors it makes no sense to have a class in most situations, in any language (other than static class, which is just a non-fortuitous name).

The fact of not storing in variable does not mean anything, after all it may be using somewhere that did not require variable yet (unless it is not used). But if you have a class it's usually interesting to build and then shut down without doing anything else, it's almost certain that this class should not exist.

The last example seems to be much worse if that is all that the class does, it creates an object, to call a method with it, and then it dies. It's just making the code slow down, occupying more memory, being less readable because it's doing that, since it makes little sense, so create a function.

If you need to have a configurable instance of something so simple use an anonymous function rather than asking an entire object for it.

If you do not have a clear and justifiable advantage, do not use. I generally request justification for the person using class in PHP and almost always has no technical justification, only policy, when it has.

    
16.07.2018 / 06:17