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
Pass arguments from array in PHP to constructor
The Reflection API can be used to pass arguments from array to constructor. This is particularly useful when you need to dynamically instantiate classes with variable constructor parameters.
ReflectionClass::newInstanceArgs
The newInstanceArgs() method creates a new class instance from given arguments −
public ReflectionClass::newInstanceArgs ([ array $args ] ) : object
It creates a new instance of the class when the arguments are passed to the constructor. Here, args refers to the array of arguments that need to be passed to the class constructor.
Example with Built-in Class
Here's an example using PHP's built-in ReflectionFunction class ?
<?php
$my_class = new ReflectionClass('ReflectionFunction');
$my_instance = $my_class->newInstanceArgs(array('substr'));
var_dump($my_instance);
?>
object(ReflectionFunction)#2 (1) { ["name"]=> string(6) "substr" }
Example with Custom Class
Here's a more practical example with a custom class that demonstrates multiple constructor arguments ?
<?php
class User {
private $name;
private $email;
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
public function getInfo() {
return "Name: " . $this->name . ", Email: " . $this->email;
}
}
$args = array("John Doe", "john@example.com");
$reflection = new ReflectionClass('User');
$user = $reflection->newInstanceArgs($args);
echo $user->getInfo();
?>
Name: John Doe, Email: john@example.com
Conclusion
ReflectionClass::newInstanceArgs() provides a flexible way to instantiate classes dynamically with constructor arguments from an array. This is especially useful in frameworks, factories, and dependency injection scenarios.
