Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP Call methods of objects in array using array_map?
In PHP, you can call methods of objects in an array using array_map() function. This is useful when you need to extract the same property or call the same method on multiple objects.
Using Anonymous Functions (PHP 5.3+)
The most straightforward approach uses anonymous functions −
<?php
class Product {
private $name;
private $price;
public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
public function getName() {
return $this->name;
}
public function getPrice() {
return $this->price;
}
}
$products = [
new Product("Laptop", 999.99),
new Product("Mouse", 25.50),
new Product("Keyboard", 75.00)
];
$names = array_map(function($obj) { return $obj->getName(); }, $products);
$prices = array_map(function($obj) { return $obj->getPrice(); }, $products);
print_r($names);
print_r($prices);
?>
Array
(
[0] => Laptop
[1] => Mouse
[2] => Keyboard
)
Array
(
[0] => 999.99
[1] => 25.5
[2] => 75
)
Using Named Functions
You can also define a separate function for better readability −
<?php
class User {
private $email;
public function __construct($email) {
$this->email = $email;
}
public function getEmail() {
return $this->email;
}
}
function extractEmail($user) {
return $user->getEmail();
}
$users = [
new User("john@example.com"),
new User("jane@example.com"),
new User("bob@example.com")
];
$emails = array_map('extractEmail', $users);
print_r($emails);
?>
Array
(
[0] => john@example.com
[1] => jane@example.com
[2] => bob@example.com
)
Performance Comparison
| Method | Performance | Readability |
|---|---|---|
| foreach loop | Faster | Good |
| array_map() with anonymous function | Slower | Excellent |
| array_map() with named function | Slower | Good |
Conclusion
Use array_map() with anonymous functions for clean, functional programming style when performance isn't critical. For better performance with large arrays, consider using foreach loops instead.
Advertisements
