How can the issue of undefined properties in PHP classes be resolved?
When working with PHP classes, undefined properties can be resolved by using magic methods like `__get()` and `__set()` to dynamically handle property access and assignment. By implementing these magic methods, you can define custom behavior for accessing and setting undefined properties within a class.
class MyClass {
private $data = [];
public function __get($name) {
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
return null;
}
public function __set($name, $value) {
$this->data[$name] = $value;
}
}
// Usage
$obj = new MyClass();
$obj->name = 'John Doe';
echo $obj->name; // Output: John Doe