【问题标题】:Cannot access self:: when no class scope is active当没有类范围处于活动状态时无法访问 self::
【发布时间】:2012-06-30 14:09:52
【问题描述】:

我正在尝试在公共静态函数中使用 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

那时我收到错误“无法访问 self:: 当没有活动的类范围时”。

如果我在inside_this 函数之外调用second_function,它可以正常工作:

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

我需要做什么才能在inside_this 函数中使用second_function

【问题讨论】:

  • 你试过闭包吗? function inside_this() use($self) {
  • 我意识到self 不是变量为时已晚...

标签: php class object scope


【解决方案1】:

尝试将您的第一个函数更改为

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

【讨论】:

    【解决方案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
    

    【讨论】:

    • 他是protected,而不是private
    • @Cole Johnson,private 的限制更多,这就是我在示例中使用它的原因。
    • @Matthew 是否有任何文档说明为什么这在 5.3 版本的 php 中不起作用,而它在 5.4 版本中起作用
    • @aravind.udayashankara,我不确定它是否明确提及,但在这里你会看到 PHP 5.4 在闭包中引入了$thisphp.net/manual/en/migration54.new-features.php。不是同一件事,但它是相关的。
    • @Matthew 非常感谢您的分享
    【解决方案3】:

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

    所以你必须这样做:

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

    【讨论】:

    • @JohnRobinson 那是因为该方法受到保护。
    • @xdazz,有没有办法将 MyClass 保存到变量中并将其传递给函数,而不是将类名 MyClass 硬编码到代码中? (否则如果我们更改类的名称,我们需要在整个文件中搜索并替换“MyClass”)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    相关资源
    最近更新 更多