note 120150 added to language.oop5.visibility

From: Date: Fri, 11 Nov 2016 15:27:03 +0000
Subject: note 120150 added to language.oop5.visibility
Groups: php.notes 
Request: Send a blank email to php-notes+get-207074@lists.php.net to get a copy of this message
> Members declared protected can be accessed only within > the class itself and by inherited classes. Members declared > as private may only be accessed by the class that defines > the member. This is not strictly true. Code outside the object can get and set private and protected members: <?php class Sealed { private $value = 'foo'; } $sealed = new Sealed; var_dump($sealed); // private $value => string(3) "foo" call_user_func(\Closure::bind( function () use ($sealed) { $sealed->value = 'BAZ'; }, null, $sealed )); var_dump($sealed); // private $value => string(3) "BAZ" ?> The magic lay in \Closure::bind, which allows an anonymous function to bind to a particular class scope. The documentation on \Closure::bind says: > If an object is given, the type of the object will be used > instead. This determines the visibility of protected and > private methods of the bound object. So, effectively, we're adding a run-time setter to $sealed, then calling that setter. This can be elaborated to generic functions that can force set and force get object members: <?php function force_set($object, $property, $value) { call_user_func(\Closure::bind( function () use ($object, $property, $value) { $object->{$property} = $value; }, null, $object )); } function force_get($object, $property) { return call_user_func(\Closure::bind( function () use ($object, $property) { return $object->{$property}; }, null, $object )); } force_set($sealed, 'value', 'quux'); var_dump(force_get($sealed, 'value')); // 'quux' ?> You should probably not rely on this ability for production quality code, but having this ability for debugging and testing is handy. ---- Server IP: 72.52.91.14 Probable Submitter: 107.15.255.60 ---- Manual Page -- http://php.net/manual/en/language.oop5.visibility.php Edit -- https://master.php.net/note/edit/120150 Del: integrated -- https://master.php.net/note/delete/120150/integrated Del: useless -- https://master.php.net/note/delete/120150/useless Del: bad code -- https://master.php.net/note/delete/120150/bad+code Del: spam -- https://master.php.net/note/delete/120150/spam Del: non-english -- https://master.php.net/note/delete/120150/non-english Del: in docs -- https://master.php.net/note/delete/120150/in+docs Del: other reasons-- https://master.php.net/note/delete/120150 Reject -- https://master.php.net/note/reject/120150 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#207074) next »