Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 907
Felix Mc Avatar asked Apr 19 '11 20:04

Felix Mc


3 Answers

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'));
}
like image 178
webbiedave Avatar answered Oct 17 '22 01:10

webbiedave


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));
like image 44
ohmusama Avatar answered Oct 16 '22 23:10

ohmusama


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 
   }
}
like image 24
Christian Avatar answered Oct 16 '22 23:10

Christian