2013-05-07 73 views
2

我嘗試調用Test3函數,但返回了這個錯誤:「致命錯誤:調用未定義的函數」。私有函數中的PHP調用函數類方法

下面是一個例子:

class Test { 
    public Test1(){ 
     return $this->Test2(); 
    } 

    private Test2(){ 
     $a = 0; 
     return Test3($a); 

     function Test3($b){ 
      $b++; 
      return $b; 
     } 
    } 
} 

如何調用Test3的功能?

+4

爲什麼你是這樣的嵌套功能擺在首位?使Test3成爲你的類中的一個單獨的方法,然後你可以將它稱爲$ this-> Test3(),並且你不會遇到像這樣的問題 – 2013-05-07 14:47:31

+0

嵌套的php函數沒有用處,它們可以被當作一個側面解析器的效果。 – 2013-05-07 14:51:29

+3

'public Test1(){'這是什麼語言? – Ejaz 2013-05-07 14:52:14

回答

6

From PHP DOC

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

使用閉

$test = new Test(); 
echo $test->Test1(); 

修改

class Test { 

    public function Test1() { 
     return $this->Test2(); 
    } 

    private function Test2() { 
     $a = 0; 

     $Test3 = function ($b) { 
      $b ++; 
      return $b; 
     }; 

     return $Test3($a); 
    } 
} 
+0

這太棒了。謝謝。 – 2013-05-07 14:59:53

+0

很好解釋:) – 2013-05-07 15:16:01

0

不知道,如果你想要一個closure或者如果你的 '內在' 功能是一個錯字。

如果它被認爲是一個單獨的方法,那麼下面是正確的語法:

class Test 
{ 

    public function Test1() 
    { 
    return $this->Test2(); 
    } 

    private function Test2() 
    { 
    $a = 0; 
    return $this->Test3($a) 
    } 

    public function Test3($b) 
    { 
    $b++ 
    return $b; 
    } 

}