Daniel Santos
Daniel Santos

Reputation: 15999

Pass a function reference to a method in PHP

I'm working with PHP array_map

I just trying to map a array like:

class myClass{ 

    private function mapMyArray(){
        $mapped = array_map(function ($d) { return $this->myFunction($d);}, $raw);
    }

    private function myFunction(){ .... }
}

It works as expected mapping a array based on a function.

but when I reffer the function like

class myClass{

    private function mapMyArray(){
        $mapped = map($this->myFunction, $raw);
    }

    private function myFunction(){ .... }
}

doest not work.

How can I only pass the function reference to the call not a inline function. is that possible?

Why does $mapped = map($raw, $this->myFunction); doesn't works?

Upvotes: 0

Views: 109

Answers (1)

aynber
aynber

Reputation: 23033

You'd need to pass the function in as a quoted string, but since you're in a class, you have to pass it in as an array. (See the documentation for callbacks, it's mostly found in the comments)

 $mapped = map($raw, [$this, 'myFunction']);

Upvotes: 2

Related Questions