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();
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.
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.
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
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