以下是执行回调函数的三个示例。
如果您像我一样,其中之一对您来说将是最直观的。
仔细看看 $callable 在每个中的定义方式的差异。
<?php
namespace App\Calculator;
class SimpleAddition
{
protected $operands = [];
public function setOperands(array $operands)
{
$this->operands = $operands;
}
function callThisOne($a, $b){
return $a + $b;
}
function returnCallThisTwo(){
$callThis = function ($a, $b){
return $a + $b;
};
return $callThis;
}
public function callbackMethodOne()
{
$callable = array($this, 'callThisOne');
return array_reduce($this->operands, $callable, null);
}
public function callbackMethodTwo()
{
$callable = $this->returnCallThisTwo();
return array_reduce($this->operands, $callable, null);
}
public function callbackMethodThree()
{
$callable = function ($a, $b){
return $a + $b;
};
return array_reduce($this->operands, $callable, null);
}
}
?>
这是单元测试:
<?php
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
use App\Calculator\Exceptons\NoOperandsException;
class SimpleAdditionTest extends TestCase
{
/**
* This will test the SimpleAddition class
*
* @return void
*/
public function test_addition_with_callback_method_one()
{
$mathObject = new \App\Calculator\SimpleAddition;
$mathObject->setOperands([2,2]);
$this->assertEquals(4, $mathObject->callbackMethodOne());
}
public function test_addition_with_callback_method_two()
{
$mathObject = new \App\Calculator\SimpleAddition;
$mathObject->setOperands([2,2]);
$this->assertEquals(4, $mathObject->callbackMethodTwo());
}
public function test_addition_with_callback_method_three()
{
$mathObject = new \App\Calculator\SimpleAddition;
$mathObject->setOperands([2,2]);
$this->assertEquals(4, $mathObject->callbackMethodThree());
}
}