How to pass a callback class static method as a parameter in PHP

2 Answers

0 votes
class Test
{
    public static function square($number)
    {
        return $number * $number;
    }
}

$object = new Test();
$array = [1, 2, 3, 4, 5, 6];
$array = array_map(['Test', 'square'], $array);

echo "<pre>";
print_r($array); 
echo "</pre>";

  
/*
run: 
 
Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
    [4] => 25
    [5] => 36
)
   
*/ 

 



answered Sep 17, 2017 by avibootz
0 votes
class Test
{
    public static function square($number)
    {
        return $number * $number;
    }
}

$object = new Test();
$array = [1, 2, 3, 4, 5, 6, 7];
$array = array_map('Test::square', $array);

echo "<pre>";
print_r($array); 
echo "</pre>";

  
/*
run: 
 
Array
(
    [0] => 1
    [1] => 4
    [2] => 9
    [3] => 16
    [4] => 25
    [5] => 36
    [6] => 49
)
   
*/   

 



answered Sep 17, 2017 by avibootz
...