Set Method
<?php
//__set() method is a Magic Method. __set() method will automatically call while assigning value to
// private propety OR Non Existing property OR assigning value to the property which is not Exist.
// When we access any private property OR Non Existing at that time __get() method will be called
//and When We try to assign value to any private property OR Non Existing Property at that time
//__set() method will be called. This is the Main difference between __get() and __set() method.
class Student
{
private $name;
public function showMessage()
{
echo $this->name;
}
public function __get($property)
{
echo "You are trying to access non Existing OR Private property ($property)". "<br>";
}
public function __set($property, $value)
{
echo "This is a Non Existing OR Private property : $property" . "<br>";
if(property_exists($this, $property))
{
$this->$property = $value;
}
else
{
echo "Property does not exists : $property";
}
}
}
$test = new Student();
//Here below, name will be stored in $property and value "Yahoo Baba" will be stored in $value in
//__set() method above.
echo $test->name;
$test->name = "Yahoo Baba";
$test->school = "hello World";
$test->showMessage();
// OUTPUT:
//You are trying to access non Existing OR Private property (name)
// This is a Non Existing OR Private property : name
// This is a Non Existing OR Private property : playing
// Property does not exists : playingYahoo Baba
?>
Comments
Post a Comment