| 
        php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login | 
  [2005-08-09 02:11 UTC] 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"
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits             
             | 
    |||||||||||||||||||||||||||||||||||||
            
                 
                Copyright © 2001-2025 The PHP GroupAll rights reserved.  | 
        Last updated: Tue Nov 04 11:00:01 2025 UTC | 
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 ) ... }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); } }