php - 上课通知 - php

标签 php oop

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

例如:

<?php

class Foo {

    static function bar () {
        ...
    }
}

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

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

我希望输出为“You called class Foo”。

我该怎么做? 谢谢:)

最佳答案

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

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

关于魔法方法的更多细节:

关于php - 上课通知 - php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31136696/

相关文章:

php - 在 PHP 中处理具有数十个(大约 50 个)属性的客户类的推荐方法是什么?

php - 大数据 : Handling SQL Insert/Update or Merge best line by line or by CSV?

PHP OOP MySQL 连接

c - 方法 vs 函数 vs 过程 vs 类?

用于从结果中删除行号的 PHP PDO FetchAll 参数

php - WordPress get_user_meta() - 是否有更好的方法来提取大量用户数据?

php - 将 PHP 错误处理程序限制在特定的命名空间

java - java中通过String创建对象

arrays - 在 Smalltalk 中读取数组中的字符串并将其转换为数组

java - 用mockito模拟twilio