2012-03-14 64 views
2

當我從我的班級調用本地方法時,如下面的示例所示,是否必須在其之前放置$this->在類中調用本地方法時需要'this'嗎?

例子:

class test{ 
    public function hello(){ 
     $this->testing(); // This is what I am using 
     testing(); // Does this work? 
    } 
    private function testing(){ 
     echo 'hello'; 
    } 
} 

我之所以問是因爲我用在它的預定義PHP函數array_map功能,現在我打算使用由我定義的函數。這就是我的意思是:

class test{ 
    public function hello(){ 
     array_map('nl2br',$array); // Using predefined PHP function 
     array_map('mynl2br',$array); // My custom function defined within this class 
    } 
    private function mynl2br(){ 
     echo 'hello'; 
    } 
} 
+9

爲什麼你不測試它是否工作? – 2012-03-14 11:59:43

+0

只是想知道:爲什麼你不試試,如果它的作品?據我所知,我不會工作。你將不得不提供'array_map(array($ this,'mynl2br'),$ array);'。有關更多信息,請參見[php手冊](http://php.net/manual/en/language.pseudo-types.php)。 – fresskoma 2012-03-14 12:01:11

+0

可能的重複http://stackoverflow.com/questions/9701509/is-this-required-when-calling-local-method-inside-a-class,http://stackoverflow.com/questions/1050598/why-does -php-require-an-explicit-reference-to-this-to-call-member-functions – Yaniro 2012-03-14 12:02:44

回答

7

是的,它是必需的。 testing()通過該名稱引用全局函數,如果該函數不存在,將導致錯誤。

但是,您可以使用$this變量進行「回調」。從the PHP manual可以看到,您需要創建一個數組,其中第一個元素是對象,第二個元素是方法名稱。所以在這裏你可以這樣做:

array_map(array($this, 'mynl2br'), $array); 
+0

我不知道你可以傳遞一個回調作爲數組!這正是我正在尋找的答案!謝謝 – 2012-03-14 12:11:14

5

測試它自己:P

的結果是testing();不會被觸發,但$this->testing();一樣。 testing();僅指類之外的函數。

<?php 
class test{ 
    public function hello(){ 
     $this->testing(); // This is what I am using 
     testing(); // Does this work? 
    } 
    private function testing(){ 
     echo 'hello'; 
    } 
} 

function testing() { 
    echo 'hi'; 
} 

$test = new test(); 
$test->hello(); // Output: hellohi 
?> 

請參閱@lonesomeday's answer爲您的問題的可能的解決方案。

+0

不相信污染全球名稱空間是一個好主意,在這裏... – lonesomeday 2012-03-14 12:04:44

+0

@lonesomeday我既不,但我知道這一切。你的答案顯然是更好的選擇。 – 2012-03-14 12:06:08

1

爲了使用一個類的方法作爲回調,你需要傳遞一個陣列包含對象實例和方法名稱,而不是只是方法名:

array_map(array($this, 'mynl2br'), $array); 

而不是

array_map('nl2br', $array); 
1

或者您可以使用瓶蓋:

array_map(function($el) { ...; return $result; }, $array); 
+0

同樣,我還沒意識到你可以在PHP中使用這些類型的回調。我只用過它在JavaScript中!感謝您的信息 – 2012-03-14 12:14:55

+0

閉包php => 5.3.0 – Joeri 2014-02-19 11:56:41

相關問題