拦截动态函数调用(如 laravel HasAttribute 特征)
Intercept dynamic function calls (like laravel HasAttribute trait)
考虑以下 class A
:
public class A
{
//...
}
和以下代码段:
$a = new A();
$value = $a->getFooValue();
如你所见getFooValue
没有在A
上定义,我想拦截函数key(在这个cas foo
) 然后用一些自定义逻辑处理它。
我正在尝试做类似于 laravel mutators where I can have for example a method called getFooAttribute
and Laravel will handle it with the HasAttribute 特征的事情。
例如,如果我调用 getFooAttribute
,laravel 将处理它,并了解 foo
,然后将执行一些检查以查找是否存在属性或增变器。
任何参考或想法将不胜感激,谢谢!
您可以通过实现神奇的 __call() 方法来拦截对对象未定义方法的调用 - 有关详细信息,请参阅 http://php.net/manual/en/language.oop5.overloading.php#object.call。
文档中的示例:
public function __call($name, $arguments)
{
echo "Calling object method '$name' " . implode(', ', $arguments). "\n";
}
考虑以下 class A
:
public class A
{
//...
}
和以下代码段:
$a = new A();
$value = $a->getFooValue();
如你所见getFooValue
没有在A
上定义,我想拦截函数key(在这个cas foo
) 然后用一些自定义逻辑处理它。
我正在尝试做类似于 laravel mutators where I can have for example a method called getFooAttribute
and Laravel will handle it with the HasAttribute 特征的事情。
例如,如果我调用 getFooAttribute
,laravel 将处理它,并了解 foo
,然后将执行一些检查以查找是否存在属性或增变器。
任何参考或想法将不胜感激,谢谢!
您可以通过实现神奇的 __call() 方法来拦截对对象未定义方法的调用 - 有关详细信息,请参阅 http://php.net/manual/en/language.oop5.overloading.php#object.call。
文档中的示例:
public function __call($name, $arguments)
{
echo "Calling object method '$name' " . implode(', ', $arguments). "\n";
}