【问题标题】:How to set PHP class VISIBLITY [duplicate]如何设置 PHP 类 VISIBLITY [重复]
【发布时间】:2018-07-20 08:02:39
【问题描述】:

如果我正在使用 PHP 设计一个框架,并且在我的框架中有一个 A 类和一个 AManager 类。

怎样才能让所有的A对象方法或类方法只能在AManager方法中调用?

如:

class A {
  public function __construct() {
    if( the calling environment is not within AManager Object Method )
      throw new Exception("error")
    else
      init..
  }
}

我曾尝试使用__callStaticdebug_backtrace 之类的:

private static function create($a,$b) {
  echo "in create";
  new Logger($a,$b);
}
public function __callStatic($name, $arguments) {
  $array = debug_backtrace(); // check environment
  var_dump($array);
  return;
  call_user_func_array([Logger::class,$name],$arguments);
}

但回溯只显示__callStatic

那么有什么方法可以满足我的要求吗?

【问题讨论】:

  • 你不能让A的方法受保护并用AManager扩展类吗?这不是完全你所追求的,但是......

标签: php


【解决方案1】:

使AManager 扩展A,然后使您的A::__construct 受到保护。这意味着除了扩展 A 的类之外,没有人可以启动此类(意味着没有 new A())。

那么在AManager有工厂函数:

class AManager extends A {
    protected static $instance;

    public static function factory() {
        if (empty(self::$instance)) {
            self::$instance = new A();
        }

        return self::$instance;
    }
}

【讨论】:

  • 但是可能会带来一些不相关的属性和方法。
【解决方案2】:

哦。那是我的错误。它适用于 A 上的 [__callStatic,debug_backtrace,call_user_func_array]。

如:

class A{
   private static $_mfriends = [AManager::class];

   private function __callStatic($name, $arguments){
       $array = debug_backtrace();
       if(count($array) >= 2){
           if(get_class($array[1]["object"]) === self::$_mfriends[0]){
                call_user_func_array([A::class,$name],$arguments);
           }
       }
       throw new Exception("denied!");
   }
   private function __construct(){
      echo "on A constructing.\n";
   }
   // if using direct new A() method instead of create(),will cause compile problem.
   private static function create(){
       return new A();
   }
}

class AManager{
    function createA(){
       return A::create();
    }
}

【讨论】:

  • 我已将 问题 标记为重复,但这个答案 - 有更多解释 - 可能值得添加到 the existing question
猜你喜欢
  • 2019-06-03
  • 2013-01-01
  • 2011-12-01
  • 2018-06-15
  • 2013-03-05
  • 2012-06-21
  • 1970-01-01
  • 1970-01-01
  • 2014-05-09
相关资源
最近更新 更多