Computer >> Computer tutorials >  >> Programming >> PHP

Pass arguments from array in PHP to constructor


The Reflection API can be used to pass arguments from array to constructor.

ReflectionClass::newInstanceArgs

The above line 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 arguments that need to be passed to the class constructor.

Example

<?php
   $my_class = new ReflectionClass('ReflectionFunction');
   $my_instance = $my_class->newInstanceArgs(array('substr'));
   var_dump($my_instance);
?>

Output

This will produce the following output −

object(ReflectionFunction)#2 (1) { ["name"]=> string(6) "substr" }