PHP: How to Create Object Variables Dynamically?
You cannot dynamically declare public properties inside a method like public $this->$var;. In PHP, property declarations are compile-time constructs, not runtime expressions. When you write public $tedi; at the class level, the parser reserves that specific slot in memory for every instance of that class. Attempting to inject new properties via code execution inside a method will result in a fatal error or simply have no effect on the object's structure in the way you expect.
To achieve dynamic behavior where an object possesses variables determined at runtime, you must bypass standard property declaration syntax. The most common and reliable approach is to use __set() and __get() magic methods. These hooks allow you to define how the object handles unknown properties written to it. By intercepting the assignment operation, you can simulate dynamic variable creation while maintaining a consistent interface for the rest of your application.
Here is how you implement this pattern:
class Object {
private $properties = [];
public function __set($name, $value) {
$this->properties[$name] = $value;
}
public function __get($name) {
if (isset($this->properties[$name])) {
return $this->properties[$name];
}
throw new \RuntimeException("Property {$name} does not exist.");
}
public function create_object_vars() {
$vars = ["tedi", "bear"];
foreach ($vars as $var) {
// Assigning null initially to allow dynamic access later,
// or set a default value.
$this->$var = null;
}
}
}
$obj = new Object();
$obj->create_object_vars();
echo $obj->tedi; // Outputs nothing (null), but accessing it triggers __get
When you call $obj->tedi, PHP looks for a property named tedi. Since it doesn't find one in the standard list, it triggers the __get() magic method. Inside that method, you check your internal storage ($this->properties) and return the value if it exists. This effectively creates a dynamic property access pattern. You can then populate these properties inside your create_object_vars function or any other method by simply assigning to $this->$var.
If your goal is specifically to initialize an array of variables dynamically without using magic methods, you might consider using a standard PHP array instead of the object structure. Objects with dynamic properties often introduce performance overhead and can complicate serialization (e.g., serialize() or json_encode()), as magic methods are not always preserved during these processes.
Another valid approach, particularly in frameworks like Laravel, is to use attributes. If you are using PHP 8.0+, you can define a dynamic list of properties that the class will strictly enforce. However, this still requires defining them in a static context relative to the class definition, not dynamically inside a method that runs later.
For strict schema enforcement where properties must exist only if added via a controlled function, magic methods remain the most flexible solution. They allow you to decouple the declaration of a property from its existence, enabling runtime validation and storage logic within __set() and __get(). This pattern ensures that your object behaves like it has native properties while giving you full control over their lifecycle.
If you are building complex domain models where dynamic attributes are required without magic method overhead, consider utilizing the built-in ArrayObject. It behaves exactly like an array but allows you to access elements using string keys, effectively providing a dynamic property bag without the complexity of custom magic methods. This is often the preferred solution in high-performance contexts where magic methods might obscure debugging or hinder type hinting tools.