What are the best practices for accessing individual values from tables in PHP classes?
When accessing individual values from tables in PHP classes, it is best practice to use getter methods to encapsulate the retrieval of data. This helps in maintaining the principle of data encapsulation and allows for easier modification of the underlying data structure in the future. By using getter methods, you can also implement additional logic or validation before returning the value to the caller.
class User {
private $name;
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
}
$user = new User();
$user->setName('John Doe');
echo $user->getName(); // Output: John Doe