phparraysclassfunctionarray-map

How to implement class methods in array_map's callable


I am trying to create a class to handle arrays but I can't seem to get array_map() to work in it.

$array = [1,2,3,4,5,6,7,8,9,10];
class test {
    public $values;

    public function adding($data) {
        $this->values = array_map($this->dash(), $data);
    }

    public function dash($item) {
        return '-' . $item . '-';
    }

}

var_dump($array);

$test = new test();
$test->adding($array);

// Expected: -1-,-2-,-3-,-4-... 
var_dump($test->values);

This outputs

array(10) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) [5]=> int(6) [6]=> int(7) [7]=> int(8) [8]=> int(9) [9]=> int(10) }

Warning: Missing argument 1 for test::dash(), called in [...]\arraytesting.php on line 11 and defined in [...]\arraytesting.php on line 15

Warning: array_map() expects parameter 1 to be a valid callback, function '--' not found or invalid function name in [...]\arraytesting.php on line 11 NULL

What am I doing wrong or does this function just not work inside classes?


Solution

  • You are specifying dash as the callback in the wrong way.

    This does not work:

    $this->classarray = array_map($this->dash(), $data);
    

    This does:

    $this->classarray = array_map([$this, 'dash'], $data);
    

    Read about the different forms a callback may take here.