Skip to content
PHP Logo

How can objects be dynamically added to object instances in PHP classes?

In PHP, objects can be dynamically added to object instances in classes by using the magic method `__set()`. This method allows you to dynamically set properties on an object that have not been declared in the class definition. By implementing `__set()`, you can handle the dynamic addition of properties and their values at runtime.

php
class MyClass {
    private $data = [];

    public function __set($name, $value) {
        $this->data[$name] = $value;
    }

    public function __get($name) {
        return $this->data[$name];
    }
}

$obj = new MyClass();
$obj->dynamicProperty = "Dynamic Value";
echo $obj->dynamicProperty; // Output: Dynamic Value