以下是执行回调函数的四个示例。
如果您像我一样,其中之一对您来说将是最直观的。
仔细看看 $callable 在每个中的定义方式的差异。重要的是要记住 array_walk() 返回一个布尔值。
<?php
namespace App\MiscTests;
class User
{
protected $fieldsArray = [];
protected $result = "";
public function setUserFields(array $fieldsArray)
{
$this->fieldsArray = $fieldsArray;
}
public function getResult()
{
return $this->result;
}
private function test_printOne($item, $key)
{
echo $key.$item;
$this->result = $key.$item;
}
private function test_printTwo(){
$callThis = function ($item, $key){
echo $key.$item;
$this->result = $key.$item;
};
return $callThis;
}
public function callbackMethodOne()
{
$callable = array($this, 'test_printOne');
return array_walk($this->fieldsArray, $callable, null);
}
public function callbackMethodTwo()
{
$callable = $this->test_printTwo();
return array_walk($this->fieldsArray, $callable, null);
}
public function callbackMethodThree()
{
$callable = function ($item, $key){
echo $key.$item;
$this->result = $key.$item;
};
return array_walk($this->fieldsArray, $callable, null);
}
public function callbackMethodAnonymous()
{
return array_walk($this->fieldsArray, function ($item, $key){
echo $key.$item;
$this->result = $key.$item;
}, null);
}
}
?>
这是我使用的单元测试:
<?php
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
class MiscUserTest extends TestCase
{
/**
* This will test the User class
*
* @return void
*/
public function test_print_with_callback_method_one()
{
$userObject = new \App\MiscTests\User;
$userObject->setUserFields(['Foo'=>'Bar1']);
$this->assertEquals(1, $userObject->callbackMethodOne());
$result = $userObject->getResult();
$this->assertEquals(0, strcmp('FooBar1', $result));
}
public function test_print_with_callback_method_two()
{
$userObject = new \App\MiscTests\User;
$userObject->setUserFields(['Foo'=>'Bar2']);
$this->assertEquals(1, $userObject->callbackMethodTwo());
$result = $userObject->getResult();
$this->assertEquals(0, strcmp('FooBar2', $result));
}
public function test_print_with_callback_method_three()
{
$userObject = new \App\MiscTests\User;
$userObject->setUserFields(['Foo'=>'Bar3']);
$this->assertEquals(1, $userObject->callbackMethodThree());
$result = $userObject->getResult();
$this->assertEquals(0, strcmp('FooBar3', $result));
}
public function test_print_with_callback_method_anonymous()
{
$userObject = new \App\MiscTests\User;
$userObject->setUserFields(['Foo'=>'Bar4']);
$this->assertEquals(1, $userObject->callbackMethodAnonymous());
$result = $userObject->getResult();
$this->assertEquals(0, strcmp('FooBar4', $result));
}
}