2010-09-14 53 views
5

php支持朋友的功能就像C++支持嗎?在php中的朋友函數?

+0

看起來它並不:http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=friend+function+php甚至維基百科似乎不提到它:http://en.wikipedia.org/wiki/Friend_function – fabrik 2010-09-14 09:03:32

+0

找不到朋友,但C++支持朋友類或函數\ – 2010-09-14 09:07:10

+1

可能重複的[PHP等價於朋友或內部](http://stackoverflow.com/questions/317835/PHP-等效的-朋友-或內部) – 2012-06-11 21:19:34

回答

3

不需要。您必須將其公開。

2

PHP不支持任何朋友般的聲明。可以使用PHP5 __get和__set方法來模擬這種情況,並且只檢查允許的朋友類的回溯,儘管執行代碼很笨拙。

這裏也有一些示例代碼和討論,對PHP的網站主題:

類HasFriends { 私人$ __朋友=陣列( '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); 
} 

}