How to “invoke” a class instance in PHP?

£可爱£侵袭症+ 提交于 2019-11-29 10:23:56
$class = 'MyClass';
$instance = new $class;

However, if your class' constructor accepts a variable number of arguments, and you hold those arguments in an array (sort of call_user_func_array), you have to use reflection:

$class = new ReflectionClass('MyClass');
$args  = array('foo', 'bar');
$instance = $class->newInstanceArgs($args);

There is also ReflectionClass::newInstance, but it does the same thing as the first option above.

Reference:

The other answers will work in PHP <= 5.5, but this task gets a lot easier in PHP 5.6 where you don't even have to use reflection. Just do:

<?php

class MyClass
{
    public function __construct($var1, $var2)
    {}
}

$class = "MyClass";
$args = ['someValue', 'someOtherValue'];

// Here's the magic
$instance = new $class(...$args);

If the number of arguments needed by the constructor is known and constant, you can (as others have suggested) do this:

$className = 'MyClass';
$obj = new $className($arg1, $arg2, etc.); 
$obj->attribute = "Hello World";

As an alternative you could use Reflection. This also means you can provide an array of constructor arguments if you don't know how many you will need.

<?php
$rf = new ReflectionClass('MyClass');
$obj = $rf->newInstanceArgs($arrayOfArguments);
$obj->attribute = "Hello World";
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!