PHP5 introduced some magic methods in classes to reduce the pain of OOP in some
cases. Two of those magic methods are introduced to set and get dynamic property
values in a class. These two magic methods are named as __get() and __set(). Let
us see how to use them:
//class.student.php
class Student
{
private $properties = array();
function __get($property)
{
return $this->properties[$property];
}
function __set($property, $value)
{
$this->properties[$property]="AutoSet {$property} as: ".$value;
}
}
?>
Now let us see the code in action. Use the class above with the following script:
$st = new Student();
$st->name = "Afif";
$st->roll=16;
echo $st->name."\n";
echo $st->roll;
?>
When you execute the preceding code, PHP recognizes immediately that no property
named name or roll exists in the class. Since the named property doesn't exist,
the __set() method is called, which then assigns the value to the newly-created
property of the class, allowing you to see the following output:
AutoSet name as: Afif
AutoSet roll as: 16
Chapter 2
[ 41 ]
Seems quite interesting, huh? Using magic methods you still have full control over
setting and retrieving property values in classes.
Pages:
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64