代码之家  ›  专栏  ›  技术社区  ›  Mazatec

是否可以限制在PHP中如何调用方法?

  •  3
  • Mazatec  · 技术社区  · 16 年前

    考虑到我的班级是这样的:

    class Methods{
        function a(){
            return 'a';
        }
    
        function b(){  
            $this->a();   
        }
    
        function c(){ 
            $this->a();
        }  
    }
    

    是否有可能确保功能a 只有被称为 从函数b?

    a() 被一些新函数调用(例如。 d() 或e () )

    6 回复  |  直到 16 年前
        1
  •  8
  •   Mark Baker    16 年前

    public, private and protected 方法。。。在想做像这样极其复杂的事情之前,至少掌握OOP的基本知识是很有用的。

        2
  •  2
  •   Tim Cooper    16 年前

    但是,如果不是,则以下代码应该适用于您:

    class Methods
    {
        private function a()
        {
            $bt = debug_backtrace();
            if(!isset($bt[1]) || $bt[1]['function'] != 'b' || $bt[1]['class'] != get_class($this))
            {
                //Call not allowed
                return NULL;
            }
        }
        function b()
        {
            //allowed
            $this->a();
        }
        function c()
        {
            //not allowed
            $this->a();
        }
    }
    
        3
  •  1
  •   Chadwick    16 年前

    closure (aka anonymous function) 在内部 要将其限制到的方法。在定义闭包的方法之外,不能访问闭包。它们通常用于定义回调并传递给其他方法,但您可以直接调用它。

    class Methods{
      function b(){
        $a = function() {
          return 'a';
        }; // don't forget the trailing ';'
    
        $a();   
      }
    
      function c(){ 
        $this->a(); // fails
      }  
    }
    

    制作方法 私有的 或 受保护的 将阻止从类外部调用它,但不会限制类内部的哪些方法可以访问它。在某种程度上,您需要信任您的代码来遵循API的使用规则。

    类通常是信任的单元封装,如果您将方法从外部使用私有化,并对其进行文档化,那么您应该能够相信它在类中得到了正确的使用。如果不是的话,也许这个类已经变得太大了,是时候重构了。

        4
  •  0
  •   Sjoerd    16 年前

    不是真的。

    • 你可以通过检查结果来检查来电者 debug_backtrace
    • 可以将其设为私有以避免从类外部调用,然后将c()移到类外部。
        5
  •  0
  •   Felix Kling    16 年前

    我认为在 调用其他方法。

    也许你的模型错了,你必须创建两个类?一节课应该是 一个逻辑单元

    如果使用单独的类,则可以使用 private keyword 论方法 a 也不能再在课堂外叫了。

        6
  •  0
  •   Lea Hayes    15 年前

    以下可能适用于你的问题。

    class First {
        public function a() {
            $second = new Second();
    
            // Works in this context!
            $second->b($this);
        }
    }
    
    class Second {
        public function b($context) {
            if (!$context instanceof First)
                throw new Exception('Can only be called from context of "First".');
            echo 'b';
        }
    }
    
    class Third {
        public function c() {
            $second = new Second();
    
            // Doesn't work out of context.
            $second->b($this);
        }
    }
    

    警告 这并不能阻止 Third 因为它可以提供对 Second . 但它确实使这个过程更加严格,而且您的文档可以说明为什么它是这样工作的。

    也许这将是有用的,它似乎适用于类似的问题,我有相当好的。

    推荐文章