Home > Backend Development > PHP Tutorial > How to call an object's method in an array using array_map?

How to call an object's method in an array using array_map?

PHPz
Release: 2023-08-19 12:12:01
forward
1345 people have browsed it

How to call an objects method in an array using array_map?

In PHP version 5.3, methods of objects in array can be called using the below code −

$props = array_map(function($obj){ return $obj->getProp(); }, $objs);
Copy after login

This will be slower than using a "for" loop because it Call a function per element −

function map($obj) {
   return $obj->getProperty();
}
$props = array_map('map', $objs);
Copy after login

Alternatively, for versions prior to PHP 5.3, you can use the following code −

function map($obj) {
   return $obj-> getProperty ();
}
$props = array_map('map', $objs);
}
Copy after login

will call the getProperty function on all objects and display the specific property. Instead of −

function encode_data($val){
   if(is_array($val)){
      return $val = array_map('encode_data', $val);
   } else {
      return utf8_encode($val);
   } 
}
$value = array_map('encode_data', $value);
print_r($value);
Copy after login

the utf8 encoded data of this value will be displayed.

The above is the detailed content of How to call an object's method in an array using array_map?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template