Get Method
<?php
//__get() method is a Magic Method. __get() method will automatically call while accessing private
//propety OR Non Existing property OR accessing the property which is not Exist.
class Abc
{
private $name = "Yahoo Baba";
private $data = ["name"=>"Yahoo Baba","course"=>"PHP","fee"=>"2000"];
// public function __get($property)
// {
// echo "You are trying to access Non Existing OR Private property($property)" . "<br>";
// }
public function __get($key)
{
if(array_key_exists($key, $this->data))
{
return $this->data[$key];
}
else
{
return "This key($key) is not defined." . "<br>";
}
}
}
$test = new Abc();
$test->name;
print_r($test->data);
echo $test->name . "<br>";
echo $test->course . "<br>";
echo $test->fee . "<br>";
echo $test->age . "<br>";
echo $test->animal;
// OUTPUT:
//This key(data) is not defined.
// Yahoo Baba
// PHP
// 2000
// This key(age) is not defined.
// This key(animal) is not defined.
?>
Comments
Post a Comment