如何使用类方法作为回调函数?

发布于 2024-09-26 04:49:42 字数 653 浏览 11 评论 0 原文

如果我在类函数内使用 array_walk 来调用同一类的另一个函数,

class user
{
   public function getUserFields($userIdsArray,$fieldsArray)
   {

     if((isNonEmptyArray($userIdsArray)) && (isNonEmptyArray($fieldsArray)))
     {
         array_walk($fieldsArray, 'test_print');
     }
   }


  private function test_print($item, $key)
  {
         //replace the $item if it matches something
  }

}

它会给出以下错误 -

警告:array_walk() [function.array-walk]:无法调用 test_print() - 函数不存在于...

那么,如何在使用 array_walk() 时指定 $this->test_print()代码>?

If I use array_walk inside a class function to call another function of the same class

class user
{
   public function getUserFields($userIdsArray,$fieldsArray)
   {

     if((isNonEmptyArray($userIdsArray)) && (isNonEmptyArray($fieldsArray)))
     {
         array_walk($fieldsArray, 'test_print');
     }
   }


  private function test_print($item, $key)
  {
         //replace the $item if it matches something
  }

}

It gives me the following error -

Warning: array_walk() [function.array-walk]: Unable to call
test_print() - function does not exist in ...

So, how do I specify $this->test_print() while using array_walk()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

丑丑阿 2024-10-03 04:49:42

如果要将类方法指定为回调,则需要指定它所属的对象:

array_walk($fieldsArray, array($this, 'test_print'));

来自 手册

实例化对象的方法作为数组传递,该数组包含索引 0 处的对象和索引 1 处的方法名称。

If you want to specify a class method as a callback, you need to specify the object it belongs to:

array_walk($fieldsArray, array($this, 'test_print'));

From the manual:

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

风渺 2024-10-03 04:49:42

如果您需要调用静态方法而不实例化该类,您可以这样做:

// since PHP 5.3
array_walk($fieldsArray, 'self::test_print');

或者从外部:

// since PHP 5.5
array_walk($fieldsArray, User::class.'::test_print');

If you need to call a static method without instantiating the class you could do so:

// since PHP 5.3
array_walk($fieldsArray, 'self::test_print');

Or from outside:

// since PHP 5.5
array_walk($fieldsArray, User::class.'::test_print');
紙鸢 2024-10-03 04:49:42

要将一个类方法作为另一个类方法中的回调函数调用,您应该执行以下操作:

public function compareFucntion() {
}

public function useCompareFunction() {
  usort($arrayToSort, [$this, 'compareFucntion'])
}

To call a class method as a callback function in another class method, you should do :

public function compareFucntion() {
}

public function useCompareFunction() {
  usort($arrayToSort, [$this, 'compareFucntion'])
}
爱人如己 2024-10-03 04:49:42

该类在多维数组中查找特定键并返回其值:

class Find_value_by_key  {
  protected $look_by_key;
  protected $look_in_array = array();
  public $result_value;

  public function get_array($look_in_array, $look_by_key) {
    $this->look_by_key = $look_by_key;
    $this->look_in_array = $look_in_array;
    $this->run_walk_through_array($this->look_in_array);

  }

  protected function walk_through_array($value, $key) {

    if (is_array($value)) {
      if ($key === $this->look_by_key) {
        $this->result_value = $value;
      } else {
        array_walk($value,[$this,'walk_through_array']);
      }
    } 

  }

  protected function run_walk_through_array($look_in_array) {
    array_walk($look_in_array,[$this,'walk_through_array']);
  }

} 

您需要将数组和特定键传递到 get_array() 中。然后调用$result_value:

$this->load->library('find_value_by_key');
$this->find_value_by_key->get_array($my_array, 'my_key');
$key_Value = $this->find_value_by_key->result_value;

This is the class which looks for a specific key in a multidimensional array and returns its value:

class Find_value_by_key  {
  protected $look_by_key;
  protected $look_in_array = array();
  public $result_value;

  public function get_array($look_in_array, $look_by_key) {
    $this->look_by_key = $look_by_key;
    $this->look_in_array = $look_in_array;
    $this->run_walk_through_array($this->look_in_array);

  }

  protected function walk_through_array($value, $key) {

    if (is_array($value)) {
      if ($key === $this->look_by_key) {
        $this->result_value = $value;
      } else {
        array_walk($value,[$this,'walk_through_array']);
      }
    } 

  }

  protected function run_walk_through_array($look_in_array) {
    array_walk($look_in_array,[$this,'walk_through_array']);
  }

} 

You need to pass the Array and the specific Key into get_array(). Then call for $result_value:

$this->load->library('find_value_by_key');
$this->find_value_by_key->get_array($my_array, 'my_key');
$key_Value = $this->find_value_by_key->result_value;
删除→记忆 2024-10-03 04:49:42

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

}

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));
    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文