PHP Doku:: Creates a new cass instance from given arguments. - reflectionclass.newinstanceargs.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzVariablen- und typbezogene ErweiterungenReflectionThe ReflectionClass classReflectionClass::newInstanceArgs

Ein Service von Reinhard Neidl - Webprogrammierung.

The ReflectionClass class

<<ReflectionClass::newInstance

ReflectionClass::setStaticPropertyValue>>

ReflectionClass::newInstanceArgs

(PHP 5 >= 5.1.3)

ReflectionClass::newInstanceArgsCreates a new cass instance from given arguments.

Beschreibung

public object ReflectionClass::newInstanceArgs ([ array $args ] )

Creates a new cass instance of the class, the given arguments are passed to the class constructor.

Warnung

Diese Funktion ist bis jetzt nicht dokumentiert. Es steht nur die Liste der Argumente zur Verfügung.

Parameter-Liste

args

The parameters to be passed to the class constructor as an array.

Rückgabewerte

Returns a new instance of the class.

Fehler/Exceptions

A ReflectionException if the class constructor is not public.

A ReflectionException if the class does not have a constructor and the args parameter contains one or more parameters.

Siehe auch


7 BenutzerBeiträge:
- Beiträge aktualisieren...
foxbunny
12.12.2010 4:23
It should be noted that the the values in the array are mapped to constructor arguments positionally, rather than by name, so using an associative array will not make any difference.
talk at stephensugden dot com
31.10.2010 0:17
This is the way I dynamically instantiate objects in my lightweight IoC container

<?php

class SimpleContainer {

 
// ...

  // Creates an instance of an object with the provided array of arguments
 
protected function instantiate($name, $args=array()){
    if(empty(
$args))
      return new
$name();                                                                                                                                                         
    else {
     
$ref = new ReflectionClass($name);
      return
$ref->newInstanceArgs($args);
    }
  }
 
// ...
}
?>

I explicitly do NOT handle the case where a user passes constructor arguments for a constructor-less class, as I this SHOULD fail.
sausage at tehsausage dot com
21.08.2010 13:14
Annoyingly, this will throw an exception for classes with no constructor even if you pass an empty array for the arguments. For generic programming you should avoid this function and use call_user_func_array with newInstance.
sarfraznawaz2005 at gmail dot com
15.12.2009 8:31
I use reflection class and also detect whether arguments are passed by reference or passed by value
and then initiate/call the method successfully with those arguments:

<?php
   
if (count($args) > 1)
    {
        if (
method_exists($class_name'__construct') === false)
        {
            exit(
"Constructor for the class <strong>$class_name</strong> does not exist, you should not pass arguments to the constructor of this class!");
        }
   
       
$refMethod = new ReflectionMethod($class_name'__construct');
       
$params = $refMethod->getParameters();
   
       
$re_args = array();
   
        foreach(
$params as $key => $param)
        {
            if (
$param->isPassedByReference())
            {
               
$re_args[$key] = &$args[$key];
            }
            else
            {
               
$re_args[$key] = $args[$key];
            }
        }
   
       
$refClass = new ReflectionClass($class_name);
       
$class_instance = $refClass->newInstanceArgs((array) $re_args);
    }
?>
kevinpeno at gmail dot com
16.09.2009 17:11
I misunderstood this function to be a sort of setter of Reflection::newInstance() arguments in an array form rather than a creator of new instances itself.

This function is equivilant to call_user_func_array() while Reflection::newInstance() is equivilant to call_user_func()
richardcook at gmail dot com
12.04.2009 23:39
the newInstanceArgs function cannot call a class' constructor if it has references in its arguments, so be careful what you pass into it:

<?php
class Foo {
    function
__construct (&$arr) {
       
$this->arr = &$arr;
    }
    function
createInstance () {
       
$reflectionClass = new ReflectionClass("Bar");
       
        return
$reflectionClass->newInstanceArgs(array($this, $this->arr));
    }
    function
mod($key, $val) {
       
$this->arr[$key] = $val;
    }
}

class
Bar {
    function
__construct (&$foo, &$arr) {
       
$this->foo = &$foo;
       
$this->arr = &$arr;
    }
    function
mod($key, $val) {
       
$this->arr[$key] = $val;
    }
}

$arr = array();

$foo = new Foo($arr);

$arr["x"] = 1;

$foo->mod("y", 2);

$bar = $foo->createInstance();

$bar->mod("z", 3);

echo
"<pre>";
print_r($arr);
print_r($foo);
print_r($bar);
echo
"</pre>";

/*
Output:
Warning: Invocation of Bar's constructor failed in [code path] on line 31

Fatal error: Call to a member function mod() on a non-object in [code path] on line 58
*/
?>
gromit at mailinator dot com
29.07.2008 10:37
Be aware that calling the method newInstanceArgs with an empty array will still call the constructor with no arguments. If the class has no constructor then it will generate an exception.

You need to check if a constructor exists before calling this method or use try and catch to act on the exception.



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)