Search code examples
phpoperatorssymbols

Why does calling a static method with only one colon not cause a parse error?


When calling the following code, I was surprised that a parse error was not thrown or other error given as this code does not look right. The colon in PHP has several uses, however, I've gone off the tracks on this one as I don't know which bucket this fits into.

The Code:

<?php
class ABC {
    static function xyz() {
        echo "I don't like the alphabet";
    }
}
ABC:xyz();

// tucked away in a strange file
function xyz() {
    echo "xyz\n";
}

Now obviously the code is missing the extra :, but the strange part is it works as if nothing is wrong. What do you suppose the output would be? Parse Error? An unkind comment about the alphabet? Undefined Constant? Partial Paamayim Nekudotayim ?(Okay! not really; joke for you well seasoned PHP experts)

But the actual output is...

xyz

In other words, the code runs with only one colon! But not as you would expect; see for yourself: https://onlinephp.io/c/e88355

Does anyone have an idea of why this is happening? The only other clue I could find is that it breaks on version 5.2.

Now obviously I could just add the : and be done with it, but I really wanted to understand why this is happening as it presents a really strange bug. Then perhaps a solution to prevent such silly things from happening again.


Solution

  • Colon is also used for statement labels that can be the target of goto.

    ABC:xyz();
    
    echo 'foo';
    goto ABC;
    

    If you don't have goto ABC in your script, the label is simply ignored.

    This is the same reason why onclick="javascript:xyz()" works in HTML/JS. Many programmers write this because they confuse it with href="javascript:xyz()" (where javascript: is the URI scheme that indicates that the rest of the URI should be executed as JS). But onXXX attributes always contain JS, and in this case javascript: is a label that's ignored.