-
Notifications
You must be signed in to change notification settings - Fork 0
/
2_5.php
66 lines (51 loc) · 1.36 KB
/
2_5.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
65
66
<?php
// ACCESS MODIFIERS, GETTERS & SETTERS
class User {
private $name;
private $age;
//Constructor
public function __construct($name,$age){
$this->name = $name;
$this->age = $age;
}
//Getters
public function getName(){
return $this->name.'<br>';
}
public function getAge(){
return $this->age.'<br>';
}
//Setters
public function setName($name){
$this->name = $name;
}
public function setAge($age){
$this->age = $age;
}
//__get MAGIC METHOD
// Provide the name of the property and get back its value
public function __get($property){
if (property_exists($this, $property)) { //check if property exists first
return $this->$property.'<br>';
}
}
//__set MAGIC METHOD
// Provide the name and value of the property and set the name to value
public function __set($property, $value){
if (property_exists($this, $property)) { //check if property exists first
$this->$property = $value;
}
return this;
}
}
$user1 = new User('Jane',39); // override with next two set statements
$user1->setName('Bob');
$user1->setAge('55');
echo $user1->getName();
echo $user1->getAge();
$user2 = new User('Josh',50); // override with next two MAGIC set statements
$user2->__set('name','Mariuma');
$user2->__set('age', 19);
echo '<br>';
echo $user2->__get('name');
echo $user2->__get('age');