2012-03-14 76 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

相关问题