Declaring __toString() stops class hoisting in CLI apps
Description
The following code:
#!/usr/bin/env php
<?php
var_dump(in_array('A', get_declared_classes()));
var_dump(in_array('B', get_declared_classes()));
class A {}
class B {
public function __toString() {}
}
var_dump(in_array('A', get_declared_classes()));
var_dump(in_array('B', get_declared_classes()));
Resulted in this output from PHP 8:
bool(true)
bool(false)
bool(true)
bool(true)
However in PHP 7 I get:
bool(true)
bool(true)
bool(true)
bool(true)
In a PHP 8 CLI app it seems declaring __toString() in a class causes it to not be hoisted.
PHP Version
PHP 8.0.15
Operating System
Rocky Linux release 8.4
That's correct: as of PHP 8.0 the __toString method implies the Stringable interface and therefore, as with any class that extends or implements another, it's no longer "hoisted".
Some more details why this is happening can be found here: https://www.npopov.com/2021/10/20/Early-binding-in-PHP.html
Thank you. I appreciate the link. The explanation in there cleared it up for me. I saw where __toString() implied the Stringable interface, I did not see where declaration of a particular function in a class could change the extended interface to one that restricts early binding. Now I know.
On Apr 7, 2022, at 10:36 PM, Alexandru Pătrănescu @.***> wrote:
Some more details why this is happening can be found here: https://www.npopov.com/2021/10/20/Early-binding-in-PHP.html https://www.npopov.com/2021/10/20/Early-binding-in-PHP.html — Reply to this email directly, view it on GitHub https://github.com/php/php-src/issues/8323#issuecomment-1092433927, or unsubscribe https://github.com/notifications/unsubscribe-auth/AICKMCOCEOJCTGY6EMY275TVD6ZWJANCNFSM5S3JL4EQ. You are receiving this because you authored the thread.