Felix Mc
Felix Mc

Reputation: 503

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

Upvotes: 15

Views: 11871

Answers (4)

Ricardo Martins
Ricardo Martins

Reputation: 6003

You can also do it inline..

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

Upvotes: 0

Christian
Christian

Reputation: 28124

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

Upvotes: 7

webbiedave
webbiedave

Reputation: 48897

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

Upvotes: 31

ohmusama
ohmusama

Reputation: 4215

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

Upvotes: 24

Related Questions