简体   繁体   English

php - 在类中使用公共函数回调的数组映射

[英]php - array map using public function callback within class

class something{   
    public function add_val( $val ){
    $array = array();
    foreach( $val as $value ) {
        $array[] = static::$post[${$value}];
    }
    return $array;
    }
    pulblic function somethingelse(){
       .... 
       ....
       $optionsArray['value'] = array_map( 'add_val', array_chunk( $drop_val, count( $optionsArray['heading_x'] ) ) );
       ....
       ....
    }
}

how can i call the add_val method within the other using array_map()??我如何使用 array_map() 在另一个中调用 add_val 方法?

Use an array that contains the object, and the method name:使用包含对象和方法名称的数组:

$optionsArray['value'] = array_map(array($this, 'add_val'), array_chunk($drop_val, count($optionsArray['heading_x'])));

You do the same for most other functions that take in callbacks as parameters, like array_walk() , call_user_func() , call_user_func_array() , and so on.您对将回调作为参数的大多数其他函数执行相同的操作,例如array_walk()call_user_func()call_user_func_array()等。

How does it work?它是如何工作的? Well, if you pass an array to the callback parameter, PHP does something similar to this (for array_map() ):好吧,如果您将数组传递给回调参数,PHP 会执行类似的操作(对于array_map() ):

if (is_array($callback)) {         // array($this, 'add_val')
    if (is_object($callback[0])) {
        $object = $callback[0];    // The object ($this)
        $method = $callback[1];    // The object method name ('add_val')

        foreach ($array as &$v) {
            // This is how you call a variable object method in PHP
            // You end up doing something like $this->add_val($v);
            $v = $object->$method($v);
        }
    }
}

// ...

return $array;

Here you can see that PHP just loops through your array, calling the method on each value.在这里您可以看到 PHP 只是循环遍历您的数组,对每个值调用该方法。 Nothing complicated to it;没有什么复杂的; again just basic object-oriented code.再次只是基本的面向对象代码。

This may or may not be how PHP does it internally, but conceptually it's the same.这可能是也可能不是 PHP 在内部的工作方式,但概念上是一样的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM