Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php array_map with static method of object

Tags:

php

array-map

I want to use array_map with a static method but I fail. Here is my code :

Class Buy {      public function payAllBills() {         $bill_list = OtherClass::getBillList();         return array_map(array(self, 'pay'), $bill_list); // Issue line     }      private static function pay($bill) {         // Some stuff         return true;     }  } 

PHP gives me the error :

Use of undefined constant self - assumed 'self' 

I have also tried :

return array_map('self::makeBean()', $model_list); 

But it doesn't work.

Do you have any idea how to use array_map with static method ?

I have already read : Can a method be used as a array_map function in PHP 5.2? but this question is about standard methods, not statics.

like image 948
Samuel Dauzon Avatar asked Jan 26 '16 09:01

Samuel Dauzon


People also ask

Can we call static method with object in PHP?

Static properties are accessed using the Scope Resolution Operator ( :: ) and cannot be accessed through the object operator ( -> ). It's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g. self , parent and static ).

What is array_ map in PHP?

Definition and Usage. The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function.

What exactly is the the difference between array_map Array_walk and Array_filter?

The resulting array of array_map has the same length as that of the largest input array; array_walk does not return an array but at the same time it cannot alter the number of elements of original array; array_filter picks only a subset of the elements of the array according to a filtering function.

Can we use this in static method PHP?

You can't use $this inside a static function, because static functions are independent of any instantiated object. Try making the function not static. Edit: By definition, static methods can be called without any instantiated object, and thus there is no meaningful use of $this inside a static method.


1 Answers

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

like image 149
Mark Baker Avatar answered Sep 19 '22 09:09

Mark Baker