PHP runs a static method before each static function

I want to be able to call a function automatically before calling any function. The problem with __callStatic is that it only executes if the method does not exist.

See code below.

I want always_run () to run before any function that is called in a static class.

class Test {

    public static function __callStatic($method, $parameters){
        echo __CLASS__ . "::" . $method;
        if (method_exists(__CLASS__, $method)) {
            self::always_run();
            forward_static_call_array(array(__CLASS__,$method),$args);
        }
    }

    public static function always_run() {
        echo "always_run";
    }

    public static function my_func() {
        echo "myfunc was called";
    }

}

Test::my_func();
// OUTPUT: always_run myfunc wascalled
+4
source share
2 answers

Creating static classes like global is always bad. You really should just create an object, then you can run any constructive code that you need in the constructor.

class Test
{
    public function __construct()
    {
        // Code run only once when the object is constructed.
    }
}

. , , , .

, : https://r.je/static-methods-bad-practice.html

+4

:

class Test {

    public static function __callStatic($method, $parameters){
        echo __CLASS__ . "::" . $method;
        if (method_exists(__CLASS__, $method)) {
            self::always_run();
            forward_static_call_array(array(__CLASS__,$method),$parameters);
        }
    }

    private static function always_run() {
        echo "always_run";
    }

    private static function my_func() {
        echo "myfunc was called";
    }

}

Test::my_func();

, .

+1

All Articles