PHP 7 Closure call( ) Method
Last Updated :
07 Jun, 2023
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 )
{
$sum = function ( $c , $d ) {
return $this ->addNumbers( $c , $d );
};
return $sum ( $a , $b );
}
public function addNumbers( $x , $y )
{
return $x + $y ;
}
}
$calculator = new Geekcalculator();
$result = $calculator ->add(69, 31);
echo $result ;
?>
|
Output:
100
Reference: https://www.php.net/manual/en/closure.call.php
Share your thoughts in the comments
Please Login to comment...