15

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 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!

4 Answers 4

31

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'));
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is the better answer. Accepted answer doesn't really answer the question, just provides an alternative for static classes, which sometimes are not desirable.
Nice sollution!
24

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

1 Comment

just to keep in mind --- namespace someNamespace; then array_walk_recursive($array, '\someNamespace\someClass::edit_value');
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 
   }
}

1 Comment

CLASS is only necessary if you're trying to call it statically.
0

You can also do it inline..

array_walk_recursive($myArray, function (&$item){
   $item = mb_convert_encoding($item, 'UTF-8');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.