calling function from within class with array_walk_recursive
This is a simplified version of a class that I have in php:
class someClass {
public function edit_array($array) {
array_walk_recursive($array, 'edit_value');
}
public function edit_value(&$value) {
//edit the value
}
}
Now sending the name of the function from within the class to array_walk_recursive开发者_如何学Python obviously does not work. However, is there a work around other than recreating array_walk_recursive using a loop (I'll save that as my last resort)? Thanks in advance!
Your methods are not defined as static so I'll assume you are instantiating. In that case, you can pass $this
:
public function edit_array($array) {
array_walk_recursive($array, array($this, 'edit_value'));
}
the function needs to be referenced staticly. I used this code with success:
<?php
class someClass {
public function edit_array($array) {
array_walk_recursive($array, 'someClass::edit_value');
}
public static function edit_value(&$value) {
echo $value;
}
}
$obj = new SomeClass();
$obj->edit_array(array(1,2,3,4,5,6,7));
Try:
class someClass {
static public function edit_array($array) {
array_walk_recursive($array, array(__CLASS__,'edit_value'));
}
static public function edit_value(&$value) {
//edit the value
}
}
NB: I used __CLASS__
so that changing class name doesn't hinder execution. You could have used "someClass"
instead as well.
Or in case of instances:
class someClass {
public function edit_array($array) {
array_walk_recursive($array, array($this,'edit_value'));
}
public function edit_value(&$value) {
//edit the value
}
}
You can also do it inline..
array_walk_recursive($myArray, function (&$item){
$item = mb_convert_encoding($item, 'UTF-8');
});
精彩评论