5

I came across something that I can't explain why it doesn't throw an error in PHP. Apologies if this is glaringly obvious to some of you, or if it has been answered before.

This is not causing any issues, it is more just an observation and a quest for understanding. I am wondering if anyone knows off the top of their head why this happens? I am just curious as it doesn't seem like it should work at all. What am I missing?

PHP version tested: PHP v7.2.12

    <?php
    class FooBar
    {
        public function foo()
        {
            anythingIWantToWrite: // this doesn't throw an error?
            return "foo";
        }

        public function baz()
        {
            baz: 'foobar'; // this doesn't throw an error?
            return "bar";
        }
    }


    $class = new FooBar();

    echo $class->foo()."\n";
    echo $class->baz();

1 Answer 1

6

Because this is valid goto syntax even if you aren't actually using it. Basically, your methods could have a goto statement in them to go to anythingIWantToWrite or baz. You just don't.

<?php
class FooBar
{
    public function foo()
    {
        goto anythingIWantToWrite;
        echo 'I am skipped';

        anythingIWantToWrite:
        return "foo";
    }

    public function baz()
    {
        goto baz;
        echo 'I am skipped';

        baz: 'foobar'; // 'foobar" is string literal that simply does nothing.
        return "bar";
    }
}


$class = new FooBar();

echo $class->foo()."\n";
echo $class->baz();

Demo

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.