-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmagic_methods.php
More file actions
54 lines (48 loc) · 1.11 KB
/
magic_methods.php
File metadata and controls
54 lines (48 loc) · 1.11 KB
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
<?php
declare(strict_types=1);
// Magic methods
class Greeter
{
public function __invoke($name): void
{
echo "Hello, $name!";
}
}
$greet = new Greeter();
$greet('John');
class Math
{
public function __call($name, $arguments)
{
if ($name === 'sum') {
return array_sum($arguments);
}
throw new Exception("Method $name doesn't exist");
}
public static function __callStatic($name, $arguments)
{
if ($name === 'product') {
return array_product($arguments);
}
throw new Exception("Static method $name doesn't exist");
}
}
$math = new Math();
echo $math->sum(1, 2, 3);
echo Math::product(2, 3, 4);
class DynamicProperties
{
private $data = [];
public function __get($name)
{
return $this->data[$name] ?? null;
}
public function __set($name, $value): void
{
echo "<br>$name,$value";
$this->data[$name] = $value;
}
}
$obj = new DynamicProperties();
$obj->email = 'test@example.com'; // Calls __set()
echo "<br>$obj->email"; // Calls __get(), outputs: test@example.com