Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 8.1.1 issue with __toString() Method - causing Class not found if instance created before declaration of class itself

I have an issue after upgrade from PHP 7.3 to 8.1.1 There is lot to be done of course, but this is kind of weird. This example is not working for me with error Fatal error:

Uncaught Error: Class "TestC" not found in C:\xampp81\htdocs\helpdesk811\test81\index.php:2 Stack trace: #0 {main} thrown in C:\xampp81\htdocs\helpdesk811\test81\index.php on line 2

<?php
$a = new TestC;
echo $a->a;
class TestC
{
    public $a = "a_value";
    public $b;
    public function __toString()
    {
        return "string";
    }
}

If I define class and create instance later, it works, but I was not able to find any documentation for this behavior.It's the same with static method (public static function foo(){echo "bar";}).

I tried 3v4l.org sandbox and it works in versions >5.0 && <8.0

like image 290
Chada Avatar asked Oct 26 '25 13:10

Chada


1 Answers

You can use a class before defining it, but only if early binding is allowed. Early binding does not work if some dependencies are not available yet, if the class uses traits or if it implements an interface. Since PHP 8 there is a new Stringable interface and every class that defines the __toString() function implicitly implements that interface, thus preventing early binding.

Nikita Popov (nikic) wrote an article about Early binding in PHP in which he mentions that this behavior is indeed not well documented.

like image 95
Remon Huijts Avatar answered Oct 29 '25 04:10

Remon Huijts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!