Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible PHP bug around static:: in PHP 5.3.3

Tags:

php

static

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!

like image 516
Jeff V Avatar asked Jun 01 '11 19:06

Jeff V


1 Answers

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.

like image 56
Tesserex Avatar answered Oct 16 '22 14:10

Tesserex