ID: 34044 Comment by: linus dot martensson at elplan-gm dot se Reported By: arendjr at gmail dot com Status: Open Bug Type: Feature/Change Request Operating System: Linux PHP Version: 5.0.4 New Comment:
I'm developing an OOP CMS, and the lack of friend objects prevents me from disallowing layouts access to unsafe internal variables. It's actually a rather severe problem when you try writing an advanced system. Previous Comments: ------------------------------------------------------------------------ [2006-06-16 21:34:45] tsteiner at nerdclub dot net In PHP 5.1, it is possible to simulate the function of friend classes with __get and __set (I think PHP 5.0 triggers an error when trying to access private properties even with __get or __set): class HasFriends { private $__friends = array('MyFriend', 'OtherFriend'); public function __get($key) { $trace = debug_backtrace(); if(isset($trace[1]['class']) && in_array($trace[1]['class'], $this->__friends)) { return $this->$key; } // normal __get() code here trigger_error('Cannot access private property ' . __CLASS__ . '::$' . $key, E_USER_ERROR); } public function __set($key, $value) { $trace = debug_backtrace(); if(isset($trace[1]['class']) && in_array($trace[1]['class'], $this->__friends)) { return $this->$key = $value; } // normal __set() code here trigger_error('Cannot access private property ' . __CLASS__ . '::$' . $key, E_USER_ERROR); } } ------------------------------------------------------------------------ [2006-01-11 00:49:08] php at lost dot co dot nz This would also be really useful for me writing unit tests so that I can run 'white box' testing on internal private methods another class (like I used to do back in the 'good' old days of PHP4... ;-) Something like this: class Util { friend class UtilTest; private static function foo() {...} } class UtilTest { if( Util::foo() != $expected ) ... } ------------------------------------------------------------------------ [2005-08-09 02:11:57] arendjr at gmail dot com Description: ------------ It would be really nice if PHP5 would support "friend classes", like C++ does. This way, classes can give access to their private members to other classes. Reproduce code: --------------- class Foo { friend class Bar; // using C++ syntax private static $a = 5; } class Bar { public static function printA() { echo Foo::$a; } } Bar::printA(); Expected result: ---------------- the above example would then print: "5" ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=34044&edit=1