4
private static function returnSameElementIfNotEmpty($item) {
    if (empty($item)) {
        return false;
    }
    else{
        return true;
    }
}


public static function clean($array) {
    return array_filter($array, 'returnSameElementIfNotEmpty');
}

当我尝试使用示例数组运行它时,我得到:

警告:array_filter() 期望参数 2 是一个有效的回调,在第 27 行的 C:\Framework\ArrayMethods.php 中找不到函数“returnSameElementIfNotEmpty”或无效的函数名

4

3 回答 3

6

试试这个:

return array_filter($array, array(__CLASS__, 'returnSameElementIfNotEmpty'));

发生错误是因为您没有调用类方法。但只是一个具有该名称的函数。在上面的示例中,我使用CLASS作为类类型来访问静态函数returnSameElementIfNotEmpty

于 2013-01-24T17:34:53.290 回答
1

太好了,在未提及的文档中。

array( CLASS , 'returnSameElementIfNotEmpty') 解决警告

更优雅:

$ArrModEmpty = array_filter($array, function($Arr){
                return (empty($Arr));
            });
于 2015-11-12T15:22:28.837 回答
0

以下是执行回调函数的三个示例。
如果您像我一样,其中之一对您来说将是最直观的。
仔细看看 $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());
    }

}
于 2022-02-19T06:24:35.003 回答