Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_map in php with callback OOP [duplicate]

Tags:

oop

php

callback

Possible Duplicate:
How to use an object method as a callback function

Usually I used array_map with procedural code, but in this case I'm working in OOP and the callback should be "this->id2areas", but It's not working. Is there anyway of put this callback with OOP?

ERROR MESSAGE: array_map() expects parameter 1 to be a valid callback, function 'this->id2area' not found or invalid function name

MY CODE =================================================================================

$this->context->assign('user_areas', implode(', ', array_map('id2area',   explode(',', $this->user['areas']))));     
explode(',', $this->user['areas']))));



function id2area($id) {//callback
    if ($id == 0) {
        return 'National';
    }
    $query = "SELECT area FROM area WHERE id = $id";
    return DB::fetch_instance()->slave->fetchColumn($query);
}    
like image 229
itaka Avatar asked Mar 17 '26 14:03

itaka


2 Answers

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

array_map(array($this, 'id2area'), $array);

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

like image 117
Vincent Robert Avatar answered Mar 20 '26 07:03

Vincent Robert


PHP callbacks for objects is a bit different then global functions.

//Global function callback
array_map('id2area', $data);

// Object function
array_map(array($object, 'id2area'), $data)
// - or -
array_map(array($this, 'id2area'), $data)

// Static class function
array_map(array('Class_Name', 'id2area'), $data)
// - or -
array_map('Class_Name::id2area', $data)

https://www.php.net/manual/en/language.types.callable.php

like image 44
rrehbein Avatar answered Mar 20 '26 07:03

rrehbein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!