代码之家  ›  专栏  ›  技术社区  ›  Pim Jager

在PHP中从变量实例化一个类?

  •  171
  • Pim Jager  · 技术社区  · 16 年前

    $var = 'bar';
    $bar = new {$var}Class('var for __construct()'); //$bar = new barClass('var for __construct()');
    

    这就是我想做的。你会怎么做?我可以像这样使用eval():

    $var = 'bar';
    eval('$bar = new '.$var.'Class(\'var for __construct()\');');
    

    但我宁愿远离eval()。没有eval(),有什么方法可以做到这一点吗?

    5 回复  |  直到 16 年前
        1
  •  248
  •   Demis Palma ツ Paul Dixon    10 年前

    首先将类名放入变量中:

    $classname=$var.'Class';
    
    $bar=new $classname("xyz");
    

    看见 Namespaces and dynamic language features

        2
  •  96
  •   csga5000    9 年前

    如果使用命名空间

    namespace com\company\lib;
    class MyClass {
    }
    

    namespace com\company\lib;
    
    //Works fine
    $i = new MyClass();
    
    $cname = 'MyClass';
    
    //Errors
    //$i = new $cname;
    
    //Works fine
    $cname = "com\\company\\lib\\".$cname;
    $i = new $cname;
    
        3
  •  64
  •   flu    10 年前

    $reflectionClass = new ReflectionClass($className);
    
    $module = $reflectionClass->newInstanceArgs($arrayOfConstructorParameters);
    

    More information on dynamic classes and parameters

    PHP>= 5.6

    Argument Unpacking :

    // The "..." is part of the language and indicates an argument array to unpack.
    $module = new $className(...$arrayOfConstructorParameters);
    

    感谢DisgruntledGoat指出这一点。

        4
  •  32
  •   ReactiveRaven NarutoBruto    11 年前
    class Test {
        public function yo() {
            return 'yoes';
        }
    }
    
    $var = 'Test';
    
    $obj = new $var();
    echo $obj->yo(); //yoes
    
        5
  •  -1
  •   pickman murimi    7 年前

    call_user_func() call_user_func_array php方法。 你可以在这里查看( call_user_func_array , call_user_func ).

    例子

    class Foo {
    static public function test() {
        print "Hello world!\n";
    }
    }
    
     call_user_func('Foo::test');//FOO is the class, test is the method both separated by ::
     //or
     call_user_func(array('Foo', 'test'));//alternatively you can pass the class and method as an array
    

    如果你有要传递给方法的参数,那么使用 call_user_func_array() 功能。

    class foo {
    function bar($arg, $arg2) {
        echo __METHOD__, " got $arg and $arg2\n";
    }
    }
    
    // Call the $foo->bar() method with 2 arguments
    call_user_func_array(array("foo", "bar"), array("three", "four"));
    //or
    //FOO is the class, bar is the method both separated by ::
    call_user_func_array("foo::bar"), array("three", "four"));