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

Asked

Viewed 249 times

1

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

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

It would be the same as wearing a function?

ExampleFunction('arg1', 'arg2');

Since I did not store in 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. I’m wrong?

So the advantage of class compared to function, is that it would give to execute methods.

And the job wouldn’t work?

( new ExampleNameClass('arg1', 'arg2') )->init();
  • 1

    You can’t run methods on functions because it supports this, but you can return a function within function (!?) and follow the same logic. I recommend reading the question PHP class vs Function

1 answer

4


It’s not the same thing, and in fact, usually, it doesn’t make much sense.

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

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

The fact that it does not store 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 is usually interesting to build and close next without doing anything else, it is almost certain that this class should not exist.

The last example seems to be much worse if that’s all the class does, you create an object, to call a method with it and then die. It’s just slowing down the code, taking up 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 instead of asking an entire object for it.

If you don’t have a clear reason and justifiable advantage, don’t use it. I generally ask for justification for the person to use class in PHP and almost always has no technical justification, only politics, when it has.

Browser other questions tagged

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