What is a getter method and how can it be used to access protected variables in PHP classes?
A getter method is a function within a class that allows access to a protected variable from outside the class. By using a getter method, you can retrieve the value of a protected variable without directly accessing it, thus maintaining encapsulation and data integrity in your PHP classes.
class MyClass {
protected $myVariable;
public function getMyVariable() {
return $this->myVariable;
}
}
$obj = new MyClass();
$obj->myVariable = "Hello, World!";
echo $obj->getMyVariable(); // Output: Hello, World!