How can arrays be used to store and manage dynamic class properties in PHP for flexibility and scalability?

Arrays can be used to store and manage dynamic class properties in PHP by allowing us to dynamically add, update, and remove properties as needed. This provides flexibility and scalability to our code, as we can easily adapt to changing requirements without having to modify the class structure itself.

class DynamicProperties {
    private $properties = [];

    public function setProperty($key, $value) {
        $this->properties[$key] = $value;
    }

    public function getProperty($key) {
        return $this->properties[$key] ?? null;
    }

    public function removeProperty($key) {
        unset($this->properties[$key]);
    }
}

// Example usage
$dynamicObj = new DynamicProperties();
$dynamicObj->setProperty('name', 'John Doe');
$dynamicObj->setProperty('age', 30);

echo $dynamicObj->getProperty('name'); // Output: John Doe

$dynamicObj->removeProperty('age');

echo $dynamicObj->getProperty('age'); // Output: null