Cannot access self:: when no class scope is active

2020-08-11 10:07发布

I am trying to use a PHP function from within a public static function like so (I've shortened things a bit):

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

That's when I get the error "Cannot access self:: when no class scope is active".

If I call second_function outside of the inside_this function, it works fine:

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

What do I need to do to be able to use second_function from within the inside_this function?

3条回答
2楼-- · 2020-08-11 10:55

Try changing your first function to

public static function first_function() {

    $function = function() {    
            $some_var = self::second_function(); //  now will work
    };               
    ///To call the function do this
    $function();
    // other code here...

} // End first_function
查看更多
我命由我不由天
3楼-- · 2020-08-11 10:56

That is because All functions in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.

So you have to do:

 function inside_this() {    
   $some_var = MyClass::second_function(); 
 }     
查看更多
狗以群分
4楼-- · 2020-08-11 11:10

Works with PHP 5.4:

<?php
class A
{
  public static function f()
  {
    $inner = function()
    {
      self::g();
    };

    $inner();
  }

  private static function g()
  {
    echo "g\n";
  }
}

A::f();

Output:

g
查看更多
登录 后发表回答