note 111379 added to closure.bindto

From: Date: Thu, 14 Feb 2013 09:30:40 +0000
Subject: note 111379 added to closure.bindto
Groups: php.notes 
Request: Send a blank email to php-notes+get-193629@lists.php.net to get a copy of this message
You can do pretty Javascript-like things with objects using closure binding: <?php trait DynamicDefinition { public function __call($name, $args) { if (is_callable($this->$name)) { return call_user_func($this->$name, $args); } else { throw new \RuntimeException("Method {$name} does not exist"); } } public function __set($name, $value) { $this->$name = is_callable($value)? $value->bindTo($this, $this): $value; } } class Foo { use DynamicDefinition; private $privateValue = 'I am private'; } $foo = new Foo; $foo->bar = function() { return $this->privateValue; }; // prints 'I am private' print $foo->bar(); ?> ---- Server IP: 69.147.83.199 Probable Submitter: 212.77.105.136 ---- Manual Page -- http://php.net/manual/en/closure.bindto.php Edit -- https://master.php.net/note/edit/111379 Del: integrated -- https://master.php.net/note/delete/111379/integrated Del: useless -- https://master.php.net/note/delete/111379/useless Del: bad code -- https://master.php.net/note/delete/111379/bad+code Del: spam -- https://master.php.net/note/delete/111379/spam Del: non-english -- https://master.php.net/note/delete/111379/non-english Del: in docs -- https://master.php.net/note/delete/111379/in+docs Del: other reasons-- https://master.php.net/note/delete/111379 Reject -- https://master.php.net/note/reject/111379 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#193629) next »