How to specify callback function when filtering array with object elements in php? -


i have array items of object type, let my_object.

the class defining my_objects has function want use filter array. how can specify function when calling array_filter?

 class my_class{      private $exclude;      public filter_function(){         return !$this->exclude;      }   }   $array=array($my_object1, $my_object2, ....);   $filtered=array_filter($array,'filter_function');//obviously not work 

my_object1 , my_object2 , ... instances of my_class , want

$my_object1->filter_function()  $my_object2->filter_function()  ,..... 

be called filtering array.

you need indicate object method in callback, using array syntax shown in php docs callbacks

class my_class{      private $exclude;      public filter_function(){         return !$this->exclude;      }   }  $array = array($my_object1, $my_object2, ....);  $classfilter = new my_class(); $filtered = array_filter($array,[$classfilter, 'filter_function']); 

in case, need create instance first, use instantiated object first element in callback, , method name second element

edit

however, if you're trying filter collection of my_class objects based on whether individual objects have exclude set, need have filter method collection:

class my_class{      private $exclude;      public filter_function(){         return !$this->exclude;      }      public static filter_collection($value){         return $value->filter_function();      }   }  $array = array($my_object1, $my_object2, ....);  $filtered = array_filter($array,['my_class', 'filter_collection']); 

Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -