instantiate a class from a variable in PHP?

php class
php class
php instantiate class from string
php get class name
php class variables
php create class dynamically
php class constructor
php dynamic class name

I know this question sounds rather vague so I will make it more clear with an example:

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

This is what I want to do. How would you do it? I could off course use eval() like this:

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

But I'd rather stay away from eval(). Is there any way to do this without eval()?


Put the classname into a variable first:

$classname=$var.'Class';

$bar=new $classname("xyz");

This is often the sort of thing you'll see wrapped up in a Factory pattern.

See Namespaces and dynamic language features for further details.

Namespaces and dynamic language features - Manual, When extending a class from another namespace that should instantiate a Thus, add the desired namespace of your target class before the variable name. I am really inspired with the knowledge that stereofrog has because most people don't even know about the reflection class and i myself did not know that we can use the reflection class to pass arguments that way. it solved my problem i was not able to find the solution to for many days.


If You Use Namespaces

In my own findings, I think it's good to mention that you (as far as I can tell) must declare the full namespace path of a class.

MyClass.php

namespace com\company\lib;
class MyClass {
}

index.php

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;

Classes and Objects - Manual, PHP 5 is very very flexible in accessing member variables and member functions. These access methods maybe look unusual and unnecessary at first glance;  I just wanted to point out that it is possible to load a class definition dynamically inside another class definition. Lukas is right that we cannot define a class inside another class, but we can include() or require() them dynamically, since every functions and classes defined in the included file will have a global scope.


How to pass dynamic constructor parameters too

If you want to pass dynamic constructor parameters to the class, you can use this code:

$reflectionClass = new ReflectionClass($className);

$module = $reflectionClass->newInstanceArgs($arrayOfConstructorParameters);

More information on dynamic classes and parameters

PHP >= 5.6

As of PHP 5.6 you can simplify this even more by using Argument Unpacking:

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

Thanks to DisgruntledGoat for pointing that out.

The Basics - Manual, In the class context, it is possible to create a new object by new self and new parent. When assigning an already created instance of a class to a new variable,​  From all the ways listed, using a variable for class method invocation or directly invoking methods on a class instance is the fastest. Using call_user_func() and call_user_func_array() would be comparatively slower than all other methods because it involves a function call.


class Test {
    public function yo() {
        return 'yoes';
    }
}

$var = 'Test';

$obj = new $var();
echo $obj->yo(); //yoes

get_class - Manual, The tested object. This parameter may be omitted when inside a class. when you create an object of class{$b object of B} which has a super class{Class A}. Instantiating a Class - posted in PHP Tutorials: Classes are great, but how do we use them? As with any programming language, the classes have to be instantiated, and the objects have to be created. The first step required is to require the file. <?php require_once(HelloWorld.class.php) ?> This assumes we have a php class named HelloWorld.class.php. As a side note, it is a convention to name


I would recommend the call_user_func() or call_user_func_arrayphp methods. You can check them out here (call_user_func_array , call_user_func).

example

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

If you have arguments you are passing to the method , then use the call_user_func_array() function.

example.

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"));

What Does This Mean in PHP -> or =>, on the right side of it in array context. This can be used to set values of any acceptable type into a corresponding index of an array. When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.


PHP, Which PHP function can be used to determine if an object is an instance of a class? Instancing a class normally (not through a variable) does not require the namespace. This seems to establish the pattern that if you are using an namespace and you have a class name in a string, you must provide the namespace with the class for the PHP engine to correctly resolve (other cases: class_exists(), interface_exists(), etc.) <?php


Object Oriented Programming in PHP, To create a new object, use the new statement to instantiate a class: <?php For any other value, a member variable named scalar will contain the value. <?php Instantiate/create your object. Classes are the blueprints/templates of php objects. Classes don’t actually become objects until you do something called: instantiation. When you instantiate a class, you create an instance of it … thus creating the object. In other words, instantiation is the process of creating an instance of an object in


What is the difference between is_a() function and instanceof in PHP , class instantiation and namespacing in PHP, and demonstrates how $​vehicleName & Model, then use resulting variable for creating class  To create a class in PHP, all you have to do is use the keyword class followed by the name of the class. We then create an object of the class vehicles and name it $car. This is a new car object we've created. After we've created this instance of a class, we can now do things with the object such as assign it properties.