Ben*_*rey 2 php class callback
当我从我的类中调用本地方法时,如下例所示,我是否必须先放入$this->它?
例:
class test{
public function hello(){
$this->testing(); // This is what I am using
testing(); // Does this work?
}
private function testing(){
echo 'hello';
}
}
Run Code Online (Sandbox Code Playgroud)
我问的原因是因为我正在使用带有预定义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';
}
}
Run Code Online (Sandbox Code Playgroud)
是的,这是必需的.testing()通过该名称引用全局函数,如果该函数不存在将导致错误.
但是,您可以使用$this变量进行"回调" .从PHP手册中可以看出,您需要创建一个数组,其中第一个元素是对象,第二个元素是方法名称.所以在这里你可以这样做:
array_map(array($this, 'mynl2br'), $array);
Run Code Online (Sandbox Code Playgroud)
自己测试一下: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
?>
Run Code Online (Sandbox Code Playgroud)
请参阅@ lonesomeday的答案,找出问题的可能解决方案.