使用一个或多个参数实例化一个新的PHP类

rof*_*fle 1 php

我有这个获取功能:

public static function fetch($class, $key)
{
    try
    {
        $obj = new $class($key);
    }
    catch(Exception $e)
    {
        return false;
    }
    return $obj;
}
Run Code Online (Sandbox Code Playgroud)

它通过调用该类的构造函数并传入键来创建一个新实例.现在,我将如何制作它以便我可以在$ key中传入一个参数数组,并让它像:

$obj = new $class($key[0], $key[1]...);
Run Code Online (Sandbox Code Playgroud)

这样它适用于一个或多个键?

希望这很清楚.

使用PHP 5

zom*_*bat 7

这是个有趣的问题.如果它不是构造函数,你试图给动态参数,那么通常你可以使用call_user_func_array().但是,由于new涉及运营商,似乎没有一种优雅的方式来做到这一点.

反思似乎是我能找到的共识.以下代码片段取自call_user_func_array()上的用户注释,并很好地说明了用法:

<?php

// arguments you wish to pass to constructor of new object
$args = array('a', 'b');

// class name of new object
$className = 'myCommand';

// make a reflection object
$reflectionObj = new ReflectionClass($className);

// use Reflection to create a new instance, using the $args
$command = $reflectionObj->newInstanceArgs($args);

// this is the same as: new myCommand('a', 'b');
?>
Run Code Online (Sandbox Code Playgroud)

为了缩短您的情况,您可以使用:

$reflectionObject = new ReflectionClass($class);
$obj = $reflectionObject->newInstanceArgs($key);
Run Code Online (Sandbox Code Playgroud)


str*_*ger 5

使用反射

$classReflection = new ReflectionClass($class);
$obj = $classReflection->newInstanceArgs($key);
Run Code Online (Sandbox Code Playgroud)