Cannot access self:: when no class scope is active

十年热恋 提交于 2019-12-22 03:16:50

问题


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?


回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/11255095/cannot-access-self-when-no-class-scope-is-active

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!