Class test{
function test1()
{
echo 'inside test1';
}
function test2()
{
echo 'test2';
}
function test3()
{
echo 'test3';
}
}
$obj = new test;
$obj->test2();//prints test2
$obj->test3();//prints test3
现在我的问题是,
如何在任何被调用函数执行之前调用另一个函数?
在上面的情况下,我如何为每个其他函数调用自动调用“test1”函数,
这样我就可以得到输出,
test1
test2
test1
test3
目前我得到的输出为
test2
test3
我无法调用“test1”函数
可能存在的每个函数定义
有很多功能。我需要一种方法
在调用之前自动调用函数
类的任何函数。
任何替代方式也可以。
你最好的选择是神奇的方法__call http://php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods,请参见下面的示例:
<?php
class test {
function __construct(){}
private function test1(){
echo "In test1", PHP_EOL;
}
private function test2(){
echo "test2", PHP_EOL;
}
protected function test3(){
return "test3" . PHP_EOL;
}
public function __call($method,$arguments) {
if(method_exists($this, $method)) {
$this->test1();
return call_user_func_array(array($this,$method),$arguments);
}
}
}
$a = new test;
$a->test2();
echo $a->test3();
/*
* Output:
* In test1
* test2
* In test1
* test3
*/
请注意test2
and test3
在调用它们的上下文中不可见,因为protected
and private
。如果方法是公共的,上面的示例将失败。
test1
不必声明private
.
ideone.com 示例可以在这里找到 https://ideone.com/C7Ydxq
Updated:添加ideone的链接,添加带返回值的示例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)