【问题标题】:Notify on class call - php通知类调用 - php
【发布时间】:2015-06-30 11:12:28
【问题描述】:

我想要一个每次引用(调用)类时都会调用的函数。 魔术函数 autoload 做了类似的事情,但仅在引用的类不存在时才有效。 我想做一个在任何情况下都可以工作的函数。

例如:

<?php

class Foo {

    static function bar () {
        ...
    }
}

function __someMagicFunction ($name) {
    echo 'You called class ' . $name;
}

Foo::bar(); // Output: You called class Foo

我希望输出是“你叫类 Foo”。

我该怎么做? 谢谢:)

【问题讨论】:

  • 您可以创建一个代理来处理它,但通常对于实例方法来说效果更好。
  • 只使用构造函数。

标签: php oop


【解决方案1】:

嗯,没有简单的方法可以做到这一点,但这是可能的。尽管如此,不推荐您实现这一目标的方式,因为它会导致代码缓慢。然而,这里有一个简单的方法来做到这一点:

class Foo
{
    //protected, not public
    protected static function bar ()
    {
    }
    protected function nonStaticBar()
    {
    }
    public function __call($method, array $args)
    {
        //echoes you called Foo::nonStaticBar
        printf('You called %s::%s', get_class($this), $method);
        //perform the actual call
        return call_user_func_array([$this, $method], $args);
    }
    //same, but for static methods
    public static function __callStatic($method, array $args)
    {
        $calledClass = get_called_class();//for late static binding
        printf('You called %s::%s statically', $calledClass, $method);
        return call_user_func_array($calledClass . '::' . $method, $args);
    }
}
$foo = new Foo;
$foo->nonStaticBar();//output: You called Foo::nonStaticBar
Foo::bar();//output: You called Foo::bar statically

__callStatic 使用get_called_class 而不是get_class(self); 的原因是它使您能够将魔术方法声明为final,并且仍然让它们在子类中按预期工作:

class Foobar extends Foo
{}

Foobar::bar();//output: You called Foobar::bar statically

demo

有关魔术方法的更多详细信息:

【讨论】:

  • 谢谢。我已经考虑过这种方法,但我想要一个可以为任何类工作的函数,而不仅仅是那些扩展 Foo 类的函数。不用说,我不希望此类函数的实现在类本身内部。
  • @Arik:就像我说的那样,没有简单的方法可以做到这一点,除了让 all 类从基类扩展,并且根本没有任何公共方法。我可以问为什么你想这样做,因为我怀疑这里有一个 X-Y 问题
【解决方案2】:

使用

 public function __construct(){
}

【讨论】:

  • 每次创建类对象时都会调用构造函数
  • 从问题中提供的代码来看,这似乎与 static 函数调用有关。实现构造函数并不能解决这个问题。
猜你喜欢
  • 2010-11-22
  • 1970-01-01
  • 2013-12-20
  • 1970-01-01
  • 1970-01-01
  • 2016-06-30
  • 2013-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多