Hello all,

On github I reported a bug causing errors when objects go out of scope with a protected/private destructor: https://github.com/php/php-src/issues/16077

Example code: https://3v4l.org/bKijA

The magic methods documentation says:

All magic methods, with the exception of __construct(), __destruct(), and 
__clone(), must be declared as public

And true to its word __destruct can be declared protected/private without a warning, unlike other magic methods.

Other magic methods however still work even if they're declared private: https://3v4l.org/iCRSe


This lead to discussion around whether the engine should be fixed to always successfully call __destruct or __destruct should warn when not public like other magic methods, or contrarily warn when public, or whether there should be special logic stopping manual calls to __construct/__destruct to prevent double initialization as well...


But focusing on this specific issue I don't think these BC breaks are even warranted. Since it doesn't work now making it work wouldn't be a BC break unless you were relying on destructor call error handlers as some kind of cursed event dispatcher.

A github search for "private function __destruct" found a whopping 298 hits. 296 for "protected function __destruct"


The biggest implementation problem I can think of is what to do about class hierarchies. If you require all destructors to be protected (or public) that puts the onus on the programmer to ensure the parent destructor is called, but private destructors would be a headache.

It seems the protected but not private destructors idea was already implemented for PHP 7 (https://3v4l.org/6DFGp) but fell victim to a regression in 7.3.15/7.4.3 and no-one noticed because it was never added to the changelog in the first place.


Long story short I'd like to suggest:

1. Allow the engine to call protected destructors (again)
2. Warning when declaring a private destructor as with other magic methods
3. Documentation update to confirm private destructors aren't allowed


Does this sound good?

- Jonathan

Reply via email to