Is it possible to limit the method call method in PHP?

Given that my class is as follows:

class Methods{
    function a(){
        return 'a';
    }

    function b(){  
        $this->a();   
    }

    function c(){ 
        $this->a();
    }  
}

Is it possible to guarantee that function a can only be called from function b?

In the above example, the function c does not work. I could just include it in function b, but in the future I may allow a()some new functions to be called (e.g., d()or e ())

+3
source share
6 answers

, ... , , , - . , , debug_backtrace(), , ; .... .

+8

, . , , .

, , :

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();
    }
}
+2

, , ( ) , . , . , .

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

    $a();   
  }

  function c(){ 
    $this->a(); // fails
  }  
}

, . - , API.

, , , , , . , , , .

@Sjoerd, , @Mark Baker, ; .

+1

.

0

.

, , ? (- ).

, private keyword a .

0

.

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);
    }
}

Warning This does not prevent the Thirdmethod from being called , as it may provide a reference to the instance Second. But this makes the process more rigorous, and your documentation may indicate why it works this way.

Perhaps this will be useful, it seems to apply to a similar problem, which I had was not bad.

0
source

Source: https://habr.com/ru/post/1750312/


All Articles