-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy path04-magicke-getset.php
88 lines (77 loc) · 2.17 KB
/
04-magicke-getset.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
/*
* V tomto příkladu najdete ukázku simulace properties á la C# - ve třídě máme proměnné definované jako private a zpřístupněné pomocí magických metod.
* Pokud máme pro danou proměnnou definovaný getter nebo setter, tak s automaticky zavolá.
*/
/**
* Trait ObjectWithProperties - ukázka implementace properties
*/
trait ObjectWithProperties{
/**
* @param string $propertyName
* @return mixed
*/
public function __get($propertyName){
if (property_exists($this, $propertyName)){
$getterName='get'.ucfirst($propertyName);
if (method_exists($this,$getterName)){
return $this->$getterName();
}else{
return $this->$propertyName;
}
}
throw new LogicException('Property '.$propertyName.' does not exist.');
}
/**
* @param string $propertyName
* @param $newValue
* @return mixed
*/
public function __set($propertyName, $newValue){
if (property_exists($this, $propertyName)){
$setterName='set'.ucfirst($propertyName);
if (method_exists($this,$setterName)){
return $this->$setterName($newValue);
}else{
return $this->$propertyName=$newValue;
}
}
throw new LogicException('Property '.$propertyName.' does not exist.');
}
/**
* @param string $propertyName
* @return bool
*/
public function __isset($propertyName){
$getterName='get'.ucfirst($propertyName);
return (property_exists($this, $propertyName) || method_exists($this, $getterName));
}
/**
* @param string $propertyName
*/
public function __unset($propertyName){
if (property_exists($this, $propertyName)){
$this->$propertyName=null;
}
}
}
/**
* Class MojeTrida
* @property float $a;
* @property float $b
*/
class MojeTrida{
use ObjectWithProperties; //načíteme příslušný trait
private $a;
private $b;
/**
* @param float $a
*/
public function setA(float $a){
$this->a=$a*2;
}
}
$objekt = new MojeTrida();
$objekt->a = 10;
$objekt->b = 20;
echo $objekt->a + $objekt->b;