__get
and
__set
methods are called when there is an attempt either to use or to set a new value to any of the class property
class Person{
    public $firstName;
 
    public function __get($propertyName){
        echo "attempted to read property: $propertyName" . PHP_EOL;
    } 
    public function __set($propertyNane, $propertyValue){
        echo "attempted to set new value to property: $propertyNane" . PHP_EOL;
    } 
}
 
$p = new Person();
 
$p->firstName = 'Doe';
echo $p->firstName . PHP_EOL;
 
$p->lastName = 'John';
echo $p->lastName;
If the property is
public
, the methods are not going to be called (if the property does not exist, or exists but is not public, the methods will get called) If we make
$firstName
property
private
or
protected
, the methods will be called for the
$firstName
property
__get
,
__set
,
__call
and
__callStatic
are invoked when the method or property is inaccessible
by Valeri Tandilashvili
4 years ago
PHP
OOP
PHP Object Oriented Programming (OOP)
3
Pro tip: use ```triple backticks around text``` to write in code fences