Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
class something{   
    public function add_val( $val ){
    $array = array();
    foreach( $val as $value ) {
        $array[] = static::$post[${$value}];
    }
    return $array;
    }
    pulblic function somethingelse(){
       .... 
       ....
       $optionsArray['value'] = array_map( 'add_val', array_chunk( $drop_val, count( $optionsArray['heading_x'] ) ) );
       ....
       ....
    }
}

how can i call the add_val method within the other using array_map()??

share|improve this question

1 Answer

up vote 4 down vote accepted

Use an array that contains the object, and the method name:

$optionsArray['value'] = array_map(array($this, 'add_val'), array_chunk($drop_val, count($optionsArray['heading_x'])));

You do the same for most other functions that take in callbacks as parameters, like array_walk(), call_user_func(), call_user_func_array(), and so on.

How does it work? Well, if you pass an array to the callback parameter, PHP does something similar to this (for array_map()):

if (is_array($callback)) {         // array($this, 'add_val')
    if (is_object($callback[0])) {
        $object = $callback[0];    // The object ($this)
        $method = $callback[1];    // The object method name ('add_val')

        foreach ($array as &$v) {
            // This is how you call a variable object method in PHP
            // You end up doing something like $this->add_val($v);
            $v = $object->$method($v);
        }
    }
}

// ...

return $array;

Here you can see that PHP just loops through your array, calling the method on each value. Nothing complicated to it; again just basic object-oriented code.

This may or may not be how PHP does it internally, but conceptually it's the same.

share|improve this answer
cracking, good man, thanks for the info – Phil Jackson Jan 22 '11 at 12:10
how can you pass a variable other than the one from the array? array($this, 'add_val($p)') – Phil Jackson Jan 22 '11 at 12:19
@Phil: $this->add_val($p), goes back to basic PHP OOP. – BoltClock Jan 22 '11 at 12:20
im not sure whats goin on here. What does the first peramiter in the array_map do? – Phil Jackson Jan 22 '11 at 12:29
1  
@Phil: See if my explanation helps. – BoltClock Jan 22 '11 at 12:37
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.