Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this snippet not throw an error?

Tags:

syntax

php

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();
like image 593
MHewison Avatar asked Feb 23 '19 16:02

MHewison


People also ask

How to catch throw new error in Java?

Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.

Does raise exception exit function Python?

Raising an exception terminates the flow of your program, allowing the exception to bubble up the call stack. In the above example, this would let you explicitly handle TypeError later. If TypeError goes unhandled, code execution stops and you'll get an unhandled exception message.


1 Answers

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

like image 85
John Conde Avatar answered Sep 24 '22 19:09

John Conde