Open In App

PHP 7 Closure call( ) Method

Last Updated : 07 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

PHP 7 Closure::call() method can bind an object scope, along with calling the closure temporarily. It takes the argument as an object and a variable number of parameters to be bound.

Syntax:

public Closure::call(object $newThis, mixed ...$args): mixed

Parameters:  It takes two parameters, which are described below:

  • $newThis: This parameter represents an object that is used to bind the closure while making the call.
  • $args: This parameter specifies the number of arguments, i.e. more than zero, that will be passed as parameters to the closure.

Return Value: The return value for the Closure will be returned by this function.

Example 1: This code snippet declares a class “Person” with a constructor that takes two arguments  $name and $age. It then creates an instance of the “Person” class and assigns it to the variable $person. Finally, it prints the person’s name and age using the getName() and getAge() methods of the $person object.

PHP




<?php
class Person
{
    private $name;
    private $age;
  
    public function __construct($name, $age)
    {
        $this->name = $name;
        $this->age = $age;
    }
  
    public function getName()
    {
        return $this->name;
    }
  
    public function getAge()
    {
        return $this->age;
    }
}
  
$person = new Person("Geek", 23);
echo "Name: " . $person->getName() . "\n";
echo "Age: " . $person->getAge() . "\n";
?>


Output:

Name: Geek
Age: 23

Example 2:The code defines a “Geekcalculator” class with an add() method that creates a closure to call the add() method of the current object. It then uses the Closure::call() method to call the closure with the current object and the given arguments. The result is returned and printed on the screen.

PHP




<?php
class Geekcalculator
{
    public function add($a, $b)
    {
        // Create a closure that calls the `addNumbers` 
        // method of the current object
        $sum = function ($c, $d) {
            return $this->addNumbers($c, $d);
        };
  
        // Call the closure with $a and $b as arguments
        return $sum($a, $b);
    }
  
    // `addNumbers` method simply adds two numbers
    public function addNumbers($x, $y)
    {
        return $x + $y;
    }
}
  
// Create an instance of the `Geekcalculator` class
$calculator = new Geekcalculator();
  
// Call the `add` method with arguments 69 and 31
// the `add` method creates a closure that calls
// the `addNumbers` method of the `Geekcalculator`
// object, and then calls that closure with
// the provided arguments
$result = $calculator->add(69, 31);
  
// Output the result
echo $result;
?>


Output:

100

Reference: https://www.php.net/manual/en/closure.call.php



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads