Below are four examples of ways to do your callback functions.
If you're like me, one of these will be the most intuitive for you.
Look closely at the difference in how $callable is defined in each one.
It's important to remember that array_walk() returns a boolean.
<?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);
}
}
?>
Here's the unit tests I used:
<?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));
}
}
isNonEmptyArray
instead of just using!empty(...)
? – Intervale