📜 ⬆️ ⬇️

Perhaps a bug in PHP, maybe a feature ...

... and maybe - a bug in my head that was tired by evening -))

Try PHP 5.3.1, version 5.3.2 did not have time to check.

The simplest code:
abstract class First {

function init() {
echo static::DIR;
}

}

class Second extends First {

const DIR = 'test';

}

Second::init(); // "test"

')
We start, it is quite expected we receive "test". Which is logical. We use the recently appeared LSB feature, everything works correctly.

OK, add some more code:

class Third {

function test() {
Second::init(); // "test"
}

}

$third = new Third();
$third->test();


Personally, my $ third-> test () method calls the Fatal error: undefined class constant.

Judging by the xdebug output, the interpreter successfully reaches First :: init (), but does not find the First :: DIR constant, despite the explicitly indicated use of the LSB.

What to do? Panic and ad.

All you need is to add the “static” keyword to the definition of the First :: init () method.

Here is such an interesting feature.

Carefully reading the manual, we can conclude that a static call to methods that are not explicitly defined as static can only cause a warning of the E_STRICT level.
"Calling non-static methods statically generates an E_STRICT level warning."

As it turned out, there are situations when using the right keywords is not only useful, but also vital.

PS If this is my glitch associated with an incorrect understanding of the language - I beg you to inform, I want to know what is wrong.

Source: https://habr.com/ru/post/98496/


All Articles