Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call function stored in Class property in PHP

Hi I’m very new at PHP and wanted to know if you can store a function in a Class Property and then call it later.

class Route
{
  public $handler;
  //$handler is a reference to a function that I want to store and call later 
  function __construct($handler) 
  {
    $this->handler = $handler;
    //or maybe something like
    //$this->handler = fn () => $handler();

    //this works fine
    $handler();

    /*I get why this does not work since $handler is not a 
    method of this class but how would I store a function 
    and be able to call it later in a different context?*/
    $this->handler();
  }
}

How would I do something like this?

function foo()
{
  echo "success";
}

$route = new Route('foo');
$route->$handler();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use brackets when calling your property stored callable:

class Route
{
  public $handler;

  public function __construct(callable $handler) {
    $this->handler = $handler;
  }
}

$handler = static fn() => var_dump('Works');
$obj = new Route($handler);

($obj->handler)();

then

$ php test.php
string(5) "Works"

PS: I recommend to always use type hints.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading