transformers-php icon indicating copy to clipboard operation
transformers-php copied to clipboard

Question - Invocation Syntax

Open TheDigitalOrchard opened this issue 11 months ago • 1 comments

This is just a minor question, but I'm curious about the syntax being used to invoke objects as methods.

Example:

$outputs = $this->model->__invoke($modelInputs);

Is it intentional to be calling __invoke(...) directly, rather than this:

$outputs = $this->model($modelInputs);

Is there evidence that a direct method call is more efficient than the engine figuring out it needs to route the request to a magic method?

I'm asking because PHP docs specifically say this:

Caution All methods names starting with __ are reserved by PHP. Therefore, it is not recommended to use such method names unless overriding PHP's behavior.

which can be interpreted as the only time that you'd manually call a magic method was within the class that is overriding PHP's behaviour, not from outside the class definition.

TheDigitalOrchard avatar Feb 11 '25 03:02 TheDigitalOrchard

Good question 😅

The choice to explicitly call __invoke(...) instead of using $this->model($modelInputs) was mostly a preference during development. One of the main reasons was that IDEs provided better suggestions and support when calling __invoke directly, making it easier to work with.

Another key reason is how PHP handles invocable properties. If $model were a standalone instance, calling $model($modelInputs) would work fine. However, since it’s a property of a class, the correct syntax would be ($this->model)($modelInputs), which I initially found a bit awkward to use. At the time of writing the package, explicitly calling __invoke felt clearer to me. That said, I’ve grown to like the standard syntax over time.

As for performance, I’m not aware of any measurable difference between the two. It’s primarily a matter of semantics and readability rather than efficiency.

CodeWithKyrian avatar Mar 09 '25 12:03 CodeWithKyrian