DEV Community

Discussion on: PHP - Elegant method call

Collapse
 
jamiesonroberts profile image
Jamieson Roberts • Edited

Is there a reason you wouldn't just use the magic method __invoke()?

Example:

class Something
{
    public function __invoke($params)
    {
        // do something here
    }
}

And to invoke it you simply do

    $something = new Something($params);
Collapse
 
vlasales profile image
Vlastimil Pospichal • Edited
$something = Something($params);

Edit: Sorry, the right way is

$something = new Something($params); // Create object
echo $something(5); // Call the object as a function
Collapse
 
suddenlyrust profile image
Ruslan

I tried your example but it returns an Fatal Error. Do you have a working snippet for me?

Here is a link to a "Online PHP Compiler": repl.it/repls/ImpressionableCuddly...

class Something
{
  public function __invoke($params)
  {
    var_dump('Hi there 👋. I invoked myself 😁');
  }
}

$something = Something(['dev.to', 'is', 'really', 'cool']);

var_dump('Did the invoke work? 😕');
Thread Thread
 
jamiesonroberts profile image
Jamieson Roberts

Try the following as a replacement of line 11.

$something = Something;
$something(['dev.to', 'is', 'really', 'cool']);
Thread Thread
 
suddenlyrust profile image
Ruslan

Still getting following fatal error

PHP Fatal error: Uncaught Error: Call to undefined function Something() in /home/runner/main.php:12

What am I missing? 😖

repl.it/repls/EssentialMarvelousWe...

Thread Thread
 
jamiesonroberts profile image
Jamieson Roberts • Edited

You are missing the class instantiation (new), but I think that is my fault, I copied the wrong thing.

<?php

class Something
{
  public function __invoke($params)
  {
    var_dump('Hi there 👋. I invoked myself 😁');
  }
}

$something = new Something();
$something(['dev.to', 'is', 'really', 'cool']);

var_dump('Did the invoke work? 😕');
Thread Thread
 
suddenlyrust profile image
Ruslan

It's working now 🥳 we found the missing key to the puzzle. The invoke variant looked promising but at the end it still requires 2 lines of code.

But thank you Jamieson for showing me this variant. Did not know how to call the magic invoke method #TIL. This can be handy for sure 🤝

Collapse
 
suddenlyrust profile image
Ruslan

Thank you for your comment. I tried your example. But somehow the invoke method is never called 🤔. Could you help me with that?

Here is a link to a "Online PHP Compiler": repl.it/repls/DisastrousViciousFeed

class Something
{
    public function __invoke($params)
    {
          var_dump('Hi there 👋. I invoked myself 😁');
    }
}

$something = new Something(['dev.to', 'is', 'really', 'cool']);

var_dump('Did the invoke work? 😕');