php array_map with static method of object
As per the documentation,
return array_map('self::pay', $model_list);
Note that your attempt included ()
in the method name string, which would be wrong
Let me extend @mark-baker's answer:
if you want to call a static method of another class, you have to put the full namespace into the quotes:
return array_map('Other\namespace\CustomClass::pay', $model_list);
Using the class per use
is not enough:
// this is not enough:// use Other\namespace\CustomClass;return array_map('CustomClass::pay', $model_list); //does not work
PHP 5.6 - 7.3:
array_map('self::pay'], $bill_list); # worksarray_map(['self', 'pay'], $bill_list); # worksarray_map('\\Some\\Name\\Space\\SomeClass::method',$array); # worksarray_map(['\\Some\\Name\\Space\\SomeClass','method'],$array); # worksuse \Some\Name\Space\SomeClass; # alias to local namespace fails:array_map('SomeClass::method',$array); # failsarray_map(['SomeClass','method'],$array); # fails
The error given is:
PHP Warning: array_map() expects parameter 1 to be a valid callback, class 'SomeClass' not found
use SomeLongClassName as Foo; # alias within namespace fails:array_map("Foo::method",$array); # failsarray_map(['Foo','method'],$array); # fails
The error given is:
PHP Warning: array_map() expects parameter 1 to be a valid callback, class 'Foo' not found
One workaround to shorten the line length and/or re-use it:
const SomeClass = '\\Some\\Name\\Space\\SomeClass';array_map([SomeClass,'method'],$array); # works
or if you use the foreign static method many times over in a class:
class MyClass{ # in PHP 7.1+ you can make this private: const SCMethod = '\\Some\\Name\\Space\\SomeClass::method'; public function myMethod($array){ return array_map(self::SCMethod, $array); # works }}