The PHP __get() and __set() methods are the magic methods. So these methods will run automatically, but when? let’s see –
PHP __get() method
The __get()
method will run when you try to access a property that does not exist or is private or protected.
In the following Test
class, you can see there is the $name
property that is private, and we trying to access through an object ($obj
).
<?php
class Test{
private $name = "John";
}
$obj = new Test();
// trying to access the private property.
echo $obj->name;
Fatal error: Cannot access private property.
After defining the __get()
method, you will not see the default error message, now __get() will handle this error.
The __get($name)
method takes a parameter that gives you the name of the property $obj
wants to access.
<?php
class Test{
private $name = "John";
function __get($var_name){
return "Sorry, you cannot access the \"{$var_name}\" property.";
}
}
$obj = new Test();
echo $obj->name;
Sorry, you cannot access the "name" property.
Some examples of the __get() method
It is totally up to how you can use it.
<?php
class Test{
private $name = "John";
function __get($var_name){
if(property_exists(__CLASS__,$var_name)){
return $this->{$var_name};
}
return "\nSorry, the property \"{$var_name}\" does not exist.\n";
}
}
$obj = new Test();
echo $obj->name;
echo $obj->apple;
John
Sorry, the property "apple" does not exist.
<?php
class Test{
private $user = [
"name" => "John",
"age" => 22,
"email" => "[email protected]",
"gender" => "Male"
];
function __get($var_name){
if(isset($this->user[$var_name])){
return $this->user[$var_name];
}
return "\nSorry, the property \"{$var_name}\" does not exist.\n";
}
}
$obj = new Test();
echo $obj->name;
echo $obj->phone;
echo $obj->email;
John
Sorry, the property "phone" does not exist.
[email protected]
PHP __set() method
The __set() method will run automatically when you assign value through an object to a private/protected property or non-existing property.
The __set($var_name, $value)
takes two parameters that give you the variable name and the value of the variable.
<?php
class Test{
private $name = "John";
function __set($var_name, $value){
echo 'Variable => "'.$var_name.'" & Value => "'.$value.'"';
}
}
$obj = new Test();
$obj->name = "Raju";
Variable => "name" & Value => "Raju"