What are the best practices for implementing getter methods in PHP classes?
When implementing getter methods in PHP classes, it is important to follow best practices to ensure clean and maintainable code. One common approach is to use the magic method `__get()` to dynamically retrieve properties, allowing for flexibility in accessing class properties. Additionally, it is recommended to make getter methods public to allow external access to class properties while maintaining encapsulation.
class User {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
}
$user = new User('John Doe');
echo $user->name;