vvsh
vvsh

Reputation: 105

Passing an array to class contructor as params list

I want to create a class object and pass its parameters as an array.

For example:

$array = array (
     'param1' => 123,
     'param1' => 456,
     'param2' => 789
);

that must be transformed into an array list of settings and passed to the constructor:

$a = new A();

Upvotes: 0

Views: 107

Answers (3)

meathive
meathive

Reputation: 1

<?php
class A
{
  public function __construct( $var=array() ) { print_r( $var ); }
}

$a=new A( array( 'foo','bar','baz' ) );
?>

Upvotes: 0

user862010
user862010

Reputation:

You can use reflection

<?php
       class A {

              public function __construct ( ) {
                     print_r ( func_get_args ( ) ) ;
              }

       }

       $reflection = new ReflectionClass('A');
       $reflection->newInstanceArgs(array( 'a' , 'b' )) ;

Upvotes: 0

user862010
user862010

Reputation:

With the call_user_func_array http://php.net/call_user_func_array

<?php

      class A {

             public function __construct ( ) {
                    print_r ( func_get_args ( ) ) ;
             }

      }

      $A = new A();
      $params = array ( 'param' => 'value' , 'p1' => 'val' ) ;
      call_user_func_array ( array ( $A , '__construct' ) , $params ) ;

Upvotes: 1

Related Questions