Php - an array using the public callback function inside the 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 in another using array_map () ??

+4
source share
1 answer

Use the array containing 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 accept callbacks as parameters, such as array_walk() , call_user_func() , call_user_func_array() , etc.

How it works? Well, if you pass an array to a callback parameter, PHP does something similar to this (for 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 simply loops through your array, calling a method for each value. Nothing complicated about that; again just basic object oriented code.

It may or may not be the way PHP does it internally, but conceptually it is one and the same.

+8
source

Source: https://habr.com/ru/post/1336573/


All Articles