Notify of class call - php

I need a function that will be called every time it refers to a class (called). The autoload magic function does a similar thing, but only works if the reference class does not exist. I want to create a function that will work anyway.

For instance:

<?php

class Foo {

    static function bar () {
        ...
    }
}

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

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

I want the output to be "You called the Foo class."

How can i do this? Thank:)

+4
source share
2 answers

Well, there is no easy way to do this, but it is possible. However, the way you need to achieve this is not recommended, as this will lead to slow code. However, here is an easy way to do this:

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

:

+3

 public function __construct(){
}
-1

All Articles