PHP Object __invoke()

 ← Dev Articles
👍 0
👎 0

What is the __invoke() method used for in objects?  The __invoke() method is a PHP magic method that allows an object to be called as if it were a function.  It’s great for maintaining state and focusing on a single calculation.

Let’s take a look a more practical use.  In this example we will use it for issuing API requests:

 

 class HttpRequest {

   

    public function __construct(private string $url)

    {   

    }

 

    public function __invoke($data) {

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $this->url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);

        curl_close($ch);

        return $response;

    }

 }

 

 $amazon = new HttpRequest('https://api.example.com/amazon/store');

 $temu = new HttpRequest('https://api.example.com/temu/store');

 

 $amazonResponse = $amazon(['item_id'=>12333]);

 $temuResponse = $amazon(['item_id'=>12333]);