PHP run static method before each static function ← (PHP, HTML)

Solution:

Creating static classes such as this that have a global state is always bad design. You should really just be creating object, then you can run any sort of set up code you need in the constructor.

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

Static state makes such classes difficult to test and maintain. Static classes cannot be mocked, so code that depends on the class cannot be independently tested.

Here's an article to help you out: https://r.je/static-methods-bad-practice.html

Answer



Solution:

You can make the methods private:

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();

A bit of a hack really, but this isnt really an ideal situation

Source