当没有类范围处于活动状态时,无法访问self ::

JRO*_*ROB 12 php scope class object

我试图在公共静态函数中使用PHP函数(我已经缩短了一些东西):

class MyClass {

public static function first_function() {

    function inside_this() {    
            $some_var = self::second_function(); // doesnt work inside this function
    }               

    // other code here...

} // End first_function

protected static function second_function() { 

    // do stuff

} // End second_function

} // End class PayPalDimesale
Run Code Online (Sandbox Code Playgroud)

那是我收到错误"无法访问自我::当没有类活动范围时".

如果我second_functioninside_this函数外部调用,它可以正常工作:

class MyClass {

public static function first_function() {

    function inside_this() {    
            // some stuff here  
    }               

    $some_var = self::second_function(); // this works

} // End first_function

protected static function second_function() { 

    // do stuff

} // End second_function

} // End class PayPalDimesale
Run Code Online (Sandbox Code Playgroud)

我需要做什么才能second_functioninside_this函数中使用?

xda*_*azz 14

这是因为PHP中的所有函数都具有全局范围 - 即使它们是在内部定义的,它们也可以在函数外部调用,反之亦然.

所以你必须这样做:

 function inside_this() {    
   $some_var = MyClass::second_function(); 
 }     
Run Code Online (Sandbox Code Playgroud)

  • @JohnRobinson那是因为该方法受到保护. (2认同)