From 5bc445bd93153f26bc520ba6ca91a86bbc8a5804 Mon Sep 17 00:00:00 2001 From: Kyle Kaminski Date: Thu, 10 Apr 2014 00:36:37 -0500 Subject: JS like trickery in PHP, discover generic object in PHP --- oo/blank_object.php | 10 ++++++ oo/magic_methods.php | 93 ++++++++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 96 insertions(+), 7 deletions(-) create mode 100644 oo/blank_object.php diff --git a/oo/blank_object.php b/oo/blank_object.php new file mode 100644 index 0000000..25803d0 --- /dev/null +++ b/oo/blank_object.php @@ -0,0 +1,10 @@ +foo = 'bar'; + diff --git a/oo/magic_methods.php b/oo/magic_methods.php index 8d9da79..ecfe70f 100644 --- a/oo/magic_methods.php +++ b/oo/magic_methods.php @@ -1,16 +1,95 @@ 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() { - echo 'dispatching ctor'; - $this->arr = array(); + $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]); } - abstract protected function foo(); } -class Derived extends Base { +echo "
\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 '
' -} \ No newline at end of file +?> -- cgit v1.2.3