Design question / PHP: I have a class with methods. I would like to call to an external function anytime when any of the methods within the class is called. I would like to make it generic so anytime I add another method, the flow works with this method too.
Simplified example:
<?php
function foo()
{
return true;
}
class ABC {
public function a()
{
echo 'a';
}
public function b()
{
echo 'b';
}
}
?>
I need to call to foo() before a() or b() anytime are called.
How can I achieve this?
Protect your methods so they're not directly accessible from outside the class, then use the magic __call() method to control access to them, and execute them after calling your foo()
function foo()
{
echo 'In pre-execute hook', PHP_EOL;
return true;
}
class ABC {
private function a()
{
echo 'a', PHP_EOL;
}
private function b($myarg)
{
echo $myarg, ' b', PHP_EOL;
}
public function __call($method, $args) {
if(!method_exists($this, $method)) {
throw new Exception("Method doesn't exist");
}
call_user_func('foo');
call_user_func_array([$this, $method], $args);
}
}
$test = new ABC();
$test->a();
$test->b('Hello');
$test->c();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With