简体   繁体   中英

PHP: I have 2 static functions A and B. How do I bind B to A so that B can only be called within the method A?

Ex:

<?php

class BLAH {

    public static function A () 
    {
        self::B();
        //Do something
    }

    public static function B()
    {
        //Do something
    }

}

Goal: Bind B to A to make sure that B cannot be called elsewhere outside of the static method A.

I am guessing you want to make B either private or protected , and what you are going for is to make sure B can only be called from inside your class. BUT, if you really want to make sure B can only be called from A :

public static function B()
{
     $trace=debug_backtrace();
     $caller=array_shift($trace);
     if ($caller['function'] != 'A' || $caller['class'] != 'BLAH') {
          throw new Exception('Illegal function invocation');
     }
     else {
         //do something
     }
}

Simple: Protected method:

class BLAH {

    public static function A () 
    {
        self::B();
        //Do something
    }

    protected static function B()
    {
        //Do something
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM