在 php 中,有没有可能在调用类的成员函数时自动调用新函数
例如:我编写了一个具有 4 个成员函数的类。 然后我为该类创建了对象。 现在我将根据需要调用任一函数。 当我调用该类的任何一个函数时。我需要做一些 set/Logic ,我该怎么做
注意:我不愿意在定义的函数中调用新函数,也不需要为所有定义的函数编写逻辑。我正在寻找什么神奇的方法。请给我建议
Class IMAP{
Function IMAP()
{
Do something
}
Function getfolders() {
Do something
}
Function appendmessage()
{
Do something
}
//I need to call the below function whenever I am going to call any one of the function
Function checktokenexpired()
{
}
}
此类包含很多函数,我无法在所有函数中添加此函数
最佳答案
如果你不想a full-blown AOP library ,您可以从这样的小包装开始:
class AOP
{
function __construct($base, $methods) {
$this->base = $base;
$this->methods = $methods;
}
function __call($name, $args) {
$this->methods["before_$name"]($args);
$ret = call_user_func_array([$this->base, $name], $args);
$this->methods["after_$name"]($ret);
return $ret;
}
}
用法如下:
class Foo
{
function bar() {
echo "bar \n";
}
}
$foo = new AOP(new Foo, [
'before_bar' => function() { echo "BEFORE\n"; },
'after_bar' => function() { echo "AFTER\n"; },
]);
$foo->bar(); // prints BEFORE...bar...AFTER
关于php - 如何在调用类的成员函数时自动调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25921641/