0
class Test
{
    public $callback = "sqrt";

    public function cube($n)
    {
        return($n * $n * $n);
    }   

    public function cool()
    {
        $a = array(1, 2, 3, 4, 5);
        $b = array_map( $this->callback , $a);
        var_dump($b);
    }   
}

$t = new Test();
$t->cool();

In this code if $callback is set to something like intval or sqrt then it will work fine , but when i try to use cube method as callback function it is giving following error. Why so and how to call method cube from cool method as callback

enter image description here

3 Answers 3

2

In PHP, you can use an array to associate an object and a method call as a callable

array_map(array($this, $this->callback), $array);

http://php.net/manual/en/language.types.callable.php

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

$b = array_map( array($this, $this->callback) , $a);

Output is:

array
  0 => int 1
  1 => int 8
  2 => int 27
  3 => int 64
  4 => int 125

If its a static method:

$b = array_map( "Test::staticMethodName" , $a);

UPDATE:

Ok, the problem is, when you giving this parameter to your array_map, it parse, what's in the property of your class called callback. There is a string value: cube. You have no global cube function. intval and sqrt are global functions, so they will work. So you need to pass as the PHP documents says: A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

This is why my example works, because you have an instantiated method $this, and the method name in $this->callback.

And for static methods:

Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0. As of PHP 5.2.3, it is also possible to pass 'ClassName::methodName'.

2 Comments

Yes it works but i still don't understand what is going on. Will u please shed some light on the same
See my edited code, i tried to explain. Tell me if it's not clear.
0

Try this

$b = array_map(array($this, 'cube'), $a);

instead of

$b = array_map( $this->callback , $a);

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.