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
89
90
91
92
93
94
95
|
<?php
/* overloading in php refers to dynamically create undeclared data members at
* runtime, resulting JS style ability to assign properties to an object
* via -> operator, this is done by use of __set and __get magic methods, also
* it is possible to bypass data members access levels this way
*
* __call is used to resolve call to undefined/protected/private methods, or
* to perform clever yet ugly error handling
*
* http://www.php.net/manual/en/language.oop5.overloading.php
*
*/
error_reporting(E_ALL | E_STRICT);
class Base {
protected $data;
function __construct() {
$this->data = array();
}
/* gets called upon unresolved setter */
public function __set($key, $val) {
if (!is_a($val, 'Closure'))
print "calling __set('$key','$val')" . PHP_EOL;
$this->data[$key] = $val;
}
/* gets called upon unresolved getter */
public function __get($key) {
print "calling __get('$key')" . PHP_EOL;
if (array_key_exists($key, $this->data)) {
return $this->data[$key];
}
$trace = debug_backtrace();
trigger_error(
'Undefined property via __get(): ' . $key .
' in ' . $trace[0]['file'] .
' on line ' . $trace[0]['line'],
E_USER_NOTICE);
return null;
}
/* http://www.phpied.com/javascript-style-object-literals-in-php/ */
function __call($name, $args) {
if (is_callable($this->$name)) {
array_unshift($args, $this);
return call_user_func_array($this->$name, $args);
}
return null;
}
/** As of PHP 5.1.0 */
public function __isset($key)
{
echo "Is '$key' set?\n";
return isset($this->data[$key]);
}
/** As of PHP 5.1.0 */
public function __unset($key)
{
echo "Unsetting '$key'\n";
unset($this->data[$key]);
}
}
echo "<pre>\n";
$obj = new Base();
$obj->a = 1;
echo $obj->a . "\n\n";
var_dump(isset($obj->a));
unset($obj->a);
var_dump(isset($obj->a));
echo "\n";
/* JS like ability to assign a function to a property */
$obj->foo = function () {
print "hello, world! from method created at runtime!" . PHP_EOL;
};
$obj->foo();
echo '</pre>'
?>
|