I was working on some PHP around the "static::" keyword, and encountered an issue where too many static calls result in confusion as to where a method resides. It's easier to show by example:
class Class1
{
function Test()
{
return Class2::Test();
}
}
class Class2
{
function Test()
{
return static::Test2();
}
function Test2()
{
return true;
}
}
/* test 1: calling Class1::Test() statically results in expected call to Class2::Test2() */
echo "test 1: " . Class1::Test() . "\n";
/* test 2: instantiating the class causes Class1::Test2() to be called, which does not exist */
$Class1 = new Class1();
echo "test 2: " . $Class1->Test() . "\n";
I wanted to reach out and get opinions of PHP experts who can tell me whether this might be a genuine bug or simple misuse of the language.
I realize the setup may be odd with all the static calls, but it represents actual code that I came across.
Please let me know if any more information or clarification is needed. Thanks for any help in advance!
The PHP docs on late static bindings answer your question.
"late static bindings work by storing the class named in the last "non-forwarding call". In case of static method calls, this is the class explicitly named (usually the one on the left of the :: operator); in case of non static method calls, it is the class of the object. A "forwarding call" is a static one that is introduced by self::, parent::, static::" ...
Your test 1 is a static call, so when Class2::Test()
is called, it stores Class2. The static test2 call refers to the correct place in Class2
.
Your test 2 is a non static call, so it uses the class of the object in all cases, and since it is a Class1
, it can't find the method Test2
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With