Is it possible in PHP to instantiate an object from the name of a class, if the class name is stored in a string?
Create an Object of a Class in PHP To create an object of a class we use the new keyword.
$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.
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.
strings are not objects in PHP.
Yep, definitely.
$className = 'MyClass'; $object = new $className;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With