0
0
PHPprogramming~15 mins

__invoke for callable objects in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
__invoke for callable objects in PHP
📖 Scenario: Imagine you want to create a simple calculator object that can be called like a function to add two numbers.
🎯 Goal: You will build a PHP class with the __invoke magic method so that an object of this class can be used as a callable to add two numbers.
📋 What You'll Learn
Create a class named Adder
Add a __invoke method to the Adder class that takes two parameters
The __invoke method should return the sum of the two parameters
Create an object of the Adder class named adder
Call the adder object with two numbers and print the result
💡 Why This Matters
🌍 Real World
Using <code>__invoke</code> lets you create objects that act like functions, which can make your code cleaner and more flexible.
💼 Career
Understanding magic methods like <code>__invoke</code> is useful for PHP developers working on frameworks or libraries that use callable objects.
Progress0 / 4 steps
1
Create the Adder class
Create a class called Adder with no methods or properties.
PHP
Need a hint?

Use the class keyword followed by Adder and curly braces.

2
Add the __invoke method
Inside the Adder class, add a public method named __invoke that takes two parameters named $a and $b.
PHP
Need a hint?

Define a public function named __invoke with parameters $a and $b.

3
Return the sum inside __invoke
Inside the __invoke method, return the sum of $a and $b using the return statement.
PHP
Need a hint?

Use return $a + $b; to send back the sum.

4
Create object and call it like a function
Create an object named adder from the Adder class. Then call adder with the numbers 5 and 7 and print the result using echo.
PHP
Need a hint?

Create the object with new Adder(), then call it like a function with (5, 7), and print with echo.