Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instantiate a class from a variable in PHP?

People also ask

How do you initialize a class in PHP?

A constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)!

How do you declare a class variable in PHP?

The var keyword in PHP is used to declare a property or variable of class which is public by default. The var keyword is same as public when declaring variables or property of a class.

What is instantiate in PHP?

Instantiating an object means that we create a new object of a class in PHP. Before you can create an object, you must create a class. The class is the overall blueprint or template of the object.

How do you call a class in PHP?

When calling a class constant using the $classname :: constant syntax, the classname can actually be a variable. As of PHP 5.3, you can access a static class constant using a variable reference (Example: className :: $varConstant).


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.


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;

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.


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

$var = 'Test';

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