【问题标题】:friend function in php?php中的朋友函数?
【发布时间】:2010-09-14 09:01:20
【问题描述】:

php 是否像 c++ 支持的那样支持友元函数?

【问题讨论】:

标签: php


【解决方案1】:

您很可能指的是类/变量范围。在 php 中,你有:

  • 公开
  • 私人
  • 受保护

但不是friend 可见性。当对象的成员仅对其他扩展/继承对象可见时,使用 protected

更多信息:

【讨论】:

    【解决方案2】:

    没有。您必须将其公开。

    【讨论】:

      【解决方案3】:

      PHP 不支持任何类似朋友的声明。可以使用 PHP5 的 __get 和 __set 方法来模拟这一点,并仅检查允许的朋友类的回溯,尽管执行此操作的代码有点笨拙。

      PHP 网站上有一些示例代码和关于该主题的讨论:

      类 HasFriends { 私人 $__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);
      }
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-14
        • 2011-03-13
        • 2021-08-16
        • 2015-10-21
        • 1970-01-01
        • 1970-01-01
        • 2011-08-10
        • 2016-02-01
        相关资源
        最近更新 更多