Does php support friend function like as c++ supports?
Asked
Active
Viewed 1.2k times
5
-
Looks like it doesn't: http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=friend+function+php and even Wikipedia seems doesn't mention it: http://en.wikipedia.org/wiki/Friend_function – fabrik Sep 14 '10 at 09:03
-
not find friend but c++ supports friend class or function\ – Tejas Patel Sep 14 '10 at 09:07
-
1possible duplicate of [PHP equivalent of friend or internal](http://stackoverflow.com/questions/317835/php-equivalent-of-friend-or-internal) – Jun 11 '12 at 21:19
3 Answers
7
You are most likely referring to class/variable scope. In php, you have:
- public
- private
- protected
But not friend
visibility. The protected
though is used when an object's members are to be made visible only to other extending/inheriting objects.
More Info:

Sarfraz
- 377,238
- 77
- 533
- 578
2
PHP doesn't support any friend-like declarations. It's possible to simulate this using the PHP5 __get and __set methods and inspecting a backtrace for only the allowed friend classes, although the code to do it is kind of clumsy.
There's some sample code and discussion on the topic on PHP's site:
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);
}
}