簡體   English   中英

當沒有類范圍處於活動狀態時,無法訪問self ::

[英]Cannot access self:: when no class scope is active

我試圖在公共靜態函數中使用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

那是我收到錯誤“無法訪問自我::當沒有類活動范圍時”。

如果我在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 ,我需要做什么?

這是因為PHP中的所有函數都具有全局范圍 - 即使它們是在內部定義的,它們也可以在函數外部調用,反之亦然。

所以你必須這樣做:

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

適用於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

嘗試將您的第一個功能更改為

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM