2011-10-12 113 views
0

我想知道這是否可能,儘管我完全相信也許有更好的方法。我有這個腳本結構:從一個函數內部調用一個函數php oop

class Mother { 
    public function __construct() { 
     // script here 
    } 

    public function writer() { 
     if() { 
      // if true 
     } else { 
      // call function hello 
     } 
    } 

    public function hello() { 
     echo "Hello there."; 
    } 
} 

如何從writer()調用hello()?謝謝。

回答

3

像這樣

public function writer() { 
    $this->hello(); 
} 

$this是類的保留變量,被實例化任何類(通過new myClass稱呼)訪問$this,但如果您使用的是靜態類,你需要定義函數靜態和使用static::myFunction方法,例如:

class exampleClass { 
    public static function exampleFunc() { 
     static::hello(); 
    } 
    public static function hello() { 
     echo "Hello!"; 
    } 
} 
exampleClass::exampleFunc(); 
+0

感謝您提供非常快速的反饋,請問這是最佳方法嗎? –

+0

是的,這幾乎是唯一的方法,除非你靜態使用類,在這種情況下,請參考我更新後的文章中的例子,否則'$ this'是訪問同一類中的函數的最佳方式。 – Nexerus

+0

只需幾分鐘,非常有啓發性,非常感謝Nexerus。 –

0
// call function hello 
$this->hello(); 

而且,你的O它的功能在語法上是錯誤的。注意括號。

public function writer() { 
public function hello() { 
+0

感謝您的注意和反饋。真的很感激它。 –

0

在我的PHP 5.3.4安裝

public function hello() { } 

似乎到可以從另一個實例方法有兩種方式

$this->hello() 
self::hello() 

顯然,

$this 

參考到實例不會有用能夠在調用公共方法作爲類方法時使用