note 93452 added to language.oop5.decon

From: Date: Thu, 10 Sep 2009 14:48:14 +0000
Subject: note 93452 added to language.oop5.decon
Groups: php.notes 
Request: Send a blank email to php-notes+get-160412@lists.php.net to get a copy of this message
What I always found rather annoying about php5 is that I can't set the $this variable. (e.g.: to encapsulate it into a proxy. Put stuff before and after certain methods etc). I have found a workaround for that, which changes the syntax a bit of constructing an object: <?php new TestClass($p); ?> It is a bit odd, but is still readable. $p now contains a proxy object, which encapsulates TestClass. What I do is passing a reference to the class constructor. The constructor looks like this: <?php class TestClass { public function __construct(&$t){ /* Modify $this into method wrapper */ new MethodWrapper($this); /* Assign $this to $t */ $t = $this; } public function test(){ print "Hello\n"; } } ?> I give my proxy a reference to $this. In the proxy the references of $this of TestClass and the reference of the proxy are swapped: <?php class MethodWrapper { protected $object; /* Swap original and proxy object */ public function __construct(&$orig){ $swap = $orig; $orig = $this; $this->object = $swap; } /* Propagate calls to inner object, run methods before and after */ public function __call($method, $args){ $this->before(get_class($this->object),$method, $args); $out = call_user_func_array(array($this->object, $method), $args); /* push output as argument to after function */ array_unshift($args, $out); $this->after(get_class($this->object),$method, $args); return $out; } protected function after($class, $method, $args){ printf("After method: %s, %s \n", $class, $method); } protected function before($class, $method, $args){ printf("Before method: %s, %s \n", $class, $method); } } ?> Which gives the following output: <?php new TestClass($p); /* $p contains the TestClass encapsulated by the MethodWrapper class */ print_r($p); $p->test(); /* output MethodWrapper Object ( [object:protected] => TestClass Object ( ) ) Before method: TestClass, test Hello After method: TestClass */ ?> ---- Server IP: 91.199.167.18 Probable Submitter: 195.241.100.248 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.decon.php Edit -- https://master.php.net/note/edit/93452 Del: integrated -- https://master.php.net/note/delete/93452/integrated Del: useless -- https://master.php.net/note/delete/93452/useless Del: bad code -- https://master.php.net/note/delete/93452/bad+code Del: spam -- https://master.php.net/note/delete/93452/spam Del: non-english -- https://master.php.net/note/delete/93452/non-english Del: in docs -- https://master.php.net/note/delete/93452/in+docs Del: other reasons-- https://master.php.net/note/delete/93452 Reject -- https://master.php.net/note/reject/93452 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#160412) next »