Call object as function

Published Feb 03, 2018Last updated Mar 09, 2018
Call object as function

When using an object, you expect to get a method that will help you accomplish whatever you desire to do in your application.

As this class demonstrates, we are calling "accomplishedThisBehavior" method.

class MyClass {
public function __construct(){
  echo 'MyClass';
}

public function accomplishThisBehavior()
{
  echo 'Behavior Accomplished';
}
}
$myObject = new MyClass;
$myObject->accomplishThisBehavior();
// Behavior Accomplished

But how can sometimes, we see some application calling the object directly as a function.
It seems pretty weird at first when we are not used to it.

The way we use an object as a function is by adding a little tricky magic potion inside our class. The name of it is the magic method __invoke.

Here is how it is done

class MyClass {
public function __construct(){
  echo 'MyClass';
}

public function accomplishThisBehavior() {
  echo 'Behavior Accomplished';
}

public function __invoke() {
  echo 'call me as a function';
}

}
$myObject = new MyClass;
$myObject();
Discover and read more posts from Bart ehui
get started