Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

NicolasGoosen's avatar

Creating a new object from string of class name

It seems like in PHP I can do this...

$mystr = "MyClass"; new $mystr; // and suddenly I have a new MyClass object!!

How on earth does this work? Does anyone have a link to a deeper explanation of what's going on here?

Thank you!

0 likes
5 replies
NicolasGoosen's avatar

Thinking about this again, I'm not sure whether variable variables is the reason that this works. Variable variables would suggest I should be saying new $$mystr? But it works just going new $mystr... Very strange to me! What am I missing?

Snapey's avatar

not sure how/why but I would expect these also to work

new 'My' . 'Model'

new $this->model

new $this->evaluateClass()
Cronix's avatar

new is a php keyword, followed by the string of the name of the object to instantiate. Whether it's the classname, or a variable representing the string of the classname doesn't matter.

If a string containing the name of a class is used with new, a new instance of that class will be created. If the class is in a namespace, its fully qualified name must be used when doing this.

See the PHP docs for the new keyword: https://www.php.net/manual/en/language.oop5.basic.php

They have an example:

$instance = new SimpleClass();

// This can also be done with a variable:
$className = 'SimpleClass';
$instance = new $className(); // new SimpleClass()
1 like
devtiagofranca's avatar
// Way #1
$className = "App\MyClass";
$instance = new $className();

// ----------------------

// Way #2
$className = "App\MyClass";
$class = new \ReflectionClass($className);

// Create a new Instance without arguments:
$instance = $class->newInstance();

// Create a new Instance with arguments (need a contructor):
$instance = $class->newInstanceArgs(["Banana", "Apple"]);
1 like

Please or to participate in this conversation.