phpdynamic-properties

How do I make dynamic properties fatal?


In php < 9 how do I make dynamic properties fatal instead of deprecated?

I have not always the need for a magic __set() or __get() in a small utility function. And really I ask to prevent me from typos, very early.

Also my application probably will hit PHP 9 and I rather have clear early warning (I do not look at logs daily) before this happens.

EDIT: I did have a error handler in place (using MonoLog) so I extended this according to KIKKO Software recommendations. Thank you @KIKKOSoftware!


Solution

  • You could use set_error_handler() to specifically catch this warning, like so:

    set_error_handler(function (int $errorNo, string $message, string $file, int $line): bool
    {
        if ($errorNo == E_DEPRECATED) {
            throw new ErrorException($message, 0, $errorNo, $file, $line);
        }        
        return TRUE;
    });
    

    Demo: https://3v4l.org/tUivC

    If you specifically only want to do this for one warning message you could check the content of the $message string. For instance:

    if (($errorNo == E_DEPRECATED) && 
        str_contains($message, "Creation of dynamic property")) {
            throw new ErrorException($message, 0, $errorNo, $file, $line);
    }