Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can PHP instantiate an object from the name of the class as a string?

Is it possible in PHP to instantiate an object from the name of a class, if the class name is stored in a string?

like image 930
user135295 Avatar asked Sep 04 '09 03:09

user135295


People also ask

Which keyword is used to create an object from a class in PHP?

Create an Object of a Class in PHP To create an object of a class we use the new keyword.

How can I instantiate a class using namespace in PHP?

$object = new Foo_Bar(); It gets a little trickier if your class is defined in a namespace and you're instantiating it from outside of that namespace. If you're hard-coding a class, you need to use a leading backslash to reference the class.

What is the correct way of initiating a PHP class?

Basic class definitions begin with the keyword class , followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class. The class name can be any valid label, provided it is not a PHP reserved word.

Is string an object in PHP?

strings are not objects in PHP.


1 Answers

Yep, definitely.

$className = 'MyClass'; $object = new $className;  
like image 107
brianreavis Avatar answered Sep 22 '22 14:09

brianreavis