无法访问自::当没有类范围是活跃(Cannot access self:: when no clas

2019-07-30 04:28发布

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?

Answer 1:

这是因为在PHP中的所有函数都具有全局作用域 -他们即使他们里面,反之亦然定义的函数外部调用。

所以,你必须做的:

 function inside_this() {    
   $some_var = MyClass::second_function(); 
 }     


Answer 2:

工程与PHP 5.4:

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

    $inner();
  }

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

A::f();

输出:

g


Answer 3:

试着改变你的第一功能

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


文章来源: Cannot access self:: when no class scope is active