即使方法存在,也会在 PHP 中触发 __call()

发布于 2024-07-25 12:47:25 字数 372 浏览 2 评论 0原文

PHP 文档 中关于 __call() 的说明如下魔术方法:

在对象上下文中调用不可访问的方法时会触发 __call()。

有没有一种方法可以在调用实际方法之前调用 __call() ,即使方法存在? 或者,是否有其他我可以实现的钩子或提供此功能的其他方式?

如果重要的话,这是一个静态函数(我实际上更喜欢使用__callStatic)。

The PHP documentation says the following about the __call() magic method:

__call() is triggered when invoking inaccessible methods in an object context.

Is there a way I can have __call() called even when a method exists, before the actual method is called? Or, is there some other hook I can implement or another way that would provide this functionality?

If it matters, this is for a static function (and I would actually prefer to use __callStatic).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浸婚纱 2024-08-01 12:47:27

如何保护所有其他方法,并通过 __callStatic 代理它们?

namespace test\foo;

class A
{
    public static function __callStatic($method, $args)
    {
        echo __METHOD__ . "\n";

        return call_user_func_array(__CLASS__ . '::' . $method, $args);
    }

    protected static function foo()
    {
        echo __METHOD__ . "\n";
    }
}

A::foo();

How about just make all your other methods protected, and proxy them through __callStatic?

namespace test\foo;

class A
{
    public static function __callStatic($method, $args)
    {
        echo __METHOD__ . "\n";

        return call_user_func_array(__CLASS__ . '::' . $method, $args);
    }

    protected static function foo()
    {
        echo __METHOD__ . "\n";
    }
}

A::foo();
小嗷兮 2024-08-01 12:47:26

为什么不直接保护所有方法并使用 __call() 调用它们:

 class bar{
    public function __call($method, $args){
        echo "calling $method";
        //do other stuff
        //possibly do method_exists check
        return call_user_func_array(array($this, $method), $args);
    }
    protected function foo($arg){
       return $arg;
    }
 }

$bar = new bar;
$bar->foo("baz"); //echo's 'calling foo' and returns 'baz'

Why not just make all your methods protected and call them using __call():

 class bar{
    public function __call($method, $args){
        echo "calling $method";
        //do other stuff
        //possibly do method_exists check
        return call_user_func_array(array($this, $method), $args);
    }
    protected function foo($arg){
       return $arg;
    }
 }

$bar = new bar;
$bar->foo("baz"); //echo's 'calling foo' and returns 'baz'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文