Ruby and some other languages have a very convenient feature: symbols. They look like in-place constants. Now I wonder if the following approach by simulating symbols in PHP with an at sign before an unquoted string is a valid approach.
$array = [#key => "value"];
echo sprintf("%s PHP symbols with a %s\n", #testing, $array[#key]);
I understand there are certain drawbacks against formal constants and the like, which are same as for Ruby's symbols: consider typing errors. Are there any other considerations against using this approach?
If by "valid" you mean "can be run", then yes, it is a valid approach (but by that standard, it is also valid to make all of your strings into HEREDOC's). But simply because PHP will accept the syntax, does not mean that the syntax is without problems.
The first I can think of are that
You are actively suppressing an error, which costs processing time
Your co-workers will need an explanation as to what is going on, which costs developer time
You are working against the natural definitions of the language (PHP simply isn't Ruby)
Since you have to use a sigil for variables anyway, you're not actually cleaning the code.
You are suppressing an error (a notice, to be exact). not only this costs processing time as mentioned in cwallenpoole's answer, but also the error is there for a reason. The reason is:
Notice: Use of undefined constant hello - assumed 'hello' in ...
You are relying on some constant being undefined - which is exactly what the notice is trying to tell you. If a constant of that name is defined, you will grab its value instead.
In Ruby, :__LINE__ is something quite different from __LINE__. The former is a symbol - it equals itself no matter where you use it. The latter is a number, and a magical variable that changes its value on every line. In PHP, #__LINE__ is the same as __LINE__, because there is no error to suppress. Oh, and there's one special "symbol" that is extra-fun to debug: #exit, AKA #die.
In Ruby, you can use all sorts of symbols including operators and keywords. These (and many more) are all valid: :+ :* :< :<< :[] :[]= :while :case :x=. With a pair of parentheses, you can even use symbols like :case= and :while=. In PHP, none of these work. You'll end up with a parse error. It won't even be suppressed. The only exception is #[] in PHP 5.4, which produces an empty array. On the other hand, lots of PHP expressions are not valid Ruby symbols: #(1+1) === #2 #1 == #'1'
Ruby's symbols are not equal to anything else. This is the purpose of their existence. Sure, they have some nice properites like to_s and to_proc, but their original purpose is to serve as identifiers separate from any possible user input. This is sorta nice for example if you are using symbols to represent tokens in a lexer stream, such as [:lparen, 1, :plus, "rparen", :rparen]. In PHP, undefined constants are strings. In Ruby, ?test != "test". In PHP #test === "test" (assuming you dindn't define a constant named "test" to equal something else).
you can't even assume non-magic constants won't change. You can't even attribute to malice what can be explained with bad coding. Nothing like that is of worry in Ruby:
//in library code:
$this->status = #done; // bad
//outside library code:
define('done', "no"); // very bad
define(#done, "yes"); // even worse
echo #no; // prints "yes"
//in library code:
if($this->status == #done){
//won't execute
}
echo #die;
echo "this won't get printed!";
You shouldn't rely on constants being undefined, and you shouldn't use error suppressing to hide the error messages telling you that. You shouldn't use special notation to pretend two things are not equal when they are. Also, can you trust the users of your library to not redefine constants at runtime?
Warning:
The following answer contains analogies that are meant, purely to illustrate a point. Under no circumstances do I mean to even suggest you contemplate the possibility of someone (you or anyone else) actually sitting down and doing the things I mention. That way madness lies
Though other answers have explained the main issue with using #<str>, It supressing a notice, it's important to stress this a bit more.
When using the supressing # (of death) the notice does not magically dissapear it is still being issued. After a while logs will get clogged with notices, making it harder to find that one fatal error that could be in there. Even if there is no fatal error, it still slows the code down.
Why encourage people to write code that throws notices? Just because you like the ruby syntax? come on, if you don't like a language, don't use it. I know: legacy code, you have to... well then, do it, don't try to make it feel and look like Ruby. They're not the same language. Everything that reminds you of the fact that you're working with a different language should be seen like a tool. Different languages require different mindsets, and different ways of thinking about a problem.
Imagine writing Lisp, but change the syntax to SQL queries. How much bad code will that generate. The syntax forces you into an SQL mindset, whereas you should be thinking in functions.
But for God's sake, don't that way madness lies!! It's a fools errand, it's even worse than parsing HTML with regex. It'll make even Cthulhu cry like a little girl
Oh, and # not being used to supress errors once it's in common usage? Do you really believe that? So you expect a lot of people to write bad code, until some IDE plugin is released that doesn't complain about the abuse of the # sign. And then, you expect the PHP contributors to take notice, and find a new operator to supress errors?
Honestly. I don't want to be rude, but that's like expecting Microsoft to release the source of windows8, because some people have gotten used to linux being open source.
Another thing: As I said, suppressing notices isn't going to help you when debugging the code. It's well known that PHP has way to many functions (and reserved keywords) in its core/global namespace. If you, and your co-workers get in the habit of abusing the # operator, you could just end up with code like this:
$foo[#die] = [#exit, #constant];
Have fun debugging that onholy mess of unclear errors. Honestly...
The key in your code would be seen by PHP as an unknown constant.
In most languages this would halt the compiler, but PHP mutates it into a string in an effort to keep running. It throws a warning, but keeps going anyway. This is just bad, and you really don't want to be doing it, much less doing it deliberately.
# in PHP is for suppressing errors. It does nothing else.
Your #key will still be bad practice just as key would be and would function in exactly the same way, but the # will hide the error message that would normally be generated.
Using # error suppression in PHP is bad practice for a whole bunch of reasons (‡ see note below), but using it as a way to hide deliberately bad code is terrible. Please don't do this.
The fundamental point here is that you're using PHP, so you should write PHP code. Trying to write Ruby code in PHP is never going to work.
You should work with the language you're using, not against it.
‡ For some thoughts on why error suppression is bad practice, you may want to read this: Suppress error with # operator in PHP
One final thought: This thing of PHP converting unknown constants to a string exists in the language purely for legacy compatibility reasons; it's one of the really awful bits of bad language design that date back to the early days. A lot of the other bad stuff from early PHP has been deprecated in recent versions; this hasn't yet, but there's no good reason for it still to exist, so I kinda hope they find a way to deprecate this "feature" too. If they do, that will instantly stop your idea from working, regardless of any merits it may have.
Related
from some articles I read on general programming concept. I was made to know that "syntaxs are the formal rules that governs the construct of valid statement in a language" while "semantics are set of rules that give meaning to a statement of a language". from the defination of semantics, I feel it is similar to logic, if not, then please I want to know the difference between logical error and semantic error?
There seems to be lot of confusion around the definition of these terms, but here's my understanding:
Syntax relate to spelling and grammar.
Logic relate to program flow.
Semantics relate to meaning and context.
If the code fails to execute due to typos, invalid names, a missing parenthesis or some other grammatical flaw, you have a syntax error.
If the syntax is correct but a piece of code is (inadvertently) never executed, operations are not done in the correct order, the operation itself is wrong or code is operating on the wrong data, you have a logical error. Using a wrong conditional operator is a common example, so is inadvertently creating an infinite loop or mixing up (valid) names of variables or functions.
If both your program logic and syntax is correct so the code runs as intended, but the result is still wrong: you likely have a semantic error. Confusing a metric input value for an imperial value will get you there. Nothing wrong with the program, except that miles and kilometres don't add up, so your area calculation throws out the wrong number. Having a race condition is another common example.
The answer here depends on the book you are reading or the class you are in. In many areas of Computer Science, there is absolutely no difference between a Semantic Error and a Logic Error. Both mean that the program compiled, but the output was wrong. Just as often, they mean two different things. A simple example is intending to use X+1 in your program, but you typed X-1. That is a Logic Error. If you typed X+true, it would be Syntax Error if the language allowed it to pass through the parser, but the result of X+(boolean true) wasn't the same as X+1. Personally, when it comes to poorly defined terms such as this, I let people define them how they like and just remove the errors from my programs, regardless of what kind of errors they are.
Basically differentiating semantic errors and logic errors is contradictory as, first both in programming produce an result that is not to the expected function of the program and secondly logic errors result in semantic error as the program runs against expected functioning.
Just Google it thousands of answer will be in front of you with brief.
Semantic error is related to the meaning of something. it mean that it is a violation of the rules of meaning of a natural language or a programming language , suppose we are using the programming statement improperly ..the semantic error will be detected at compile time.
and the logical error is that Errors that indicate the logic used when coding the program failed to solve the problem. The logic error will not cause the program to stop working but our desired result will not be get.
if you want to see the example go to this site.....
http://newtutorial2012.blogspot.com/2012/07/differentced-between-synataxsemantic.html
Scenario:
We are in the process of converting an application from PHP 4 to PHP 5. The application needs to be able to work on PHP 4 for a little while, which means no PHP 5 specific elements can be used, yet. We are simply trying to make sure the application works on both platforms.
There are a lot of conditionals that look like this in the application:
if ($variable) { // do something }
Some of these variables end up not being defined at all and we are trying to reduce the number of errors (there's a lot of them).
To solve these errors, we are adding checks in various areas like this:
if (!isset($variable)) $variable = "";
or
if (!empty($variable)) { // do something }
Question:
Does anyone know of a simpler approach to fixing these errors. The problem is that these variables are being used across files (via includes) and defining the variable may change the logical flow in that file if its doing a check like (if (!isset($variable)) { // do something }).
The point of this question is to reduce errors and time consumption of tracking each individual use of these variables. Currently, we are having to either examine thoroughly what the variable is doing (which may take a good chunk of time), or we are doing a "fire and forget" / hope-its-fixed method of correcting.
-- Edit --
Does anyone know of a program like cppcheck for php that could somehow reference these variables or create some kind of chaining that could find errors and link possible references? (I hope that makes sense.)
AFAIK there is a code-checker that looks for uninitialized variables which works OK. You can work through it's messages, it's called PHP Mess Detector and one of it's rule covers uninitialized variables. However this can never be perfect.
Another method is to track the error messages and use them to locate the places within in the code. I've done that in the past and it worked very well, just do it in iterations and keep log of the warnings.
You can also work with a whitelist and import whitelisted variables when the request starts. Non-whitelisted submissions need to cause an access violation error to have this properly working, so this way is more work than tracking warnings albeit it might make your application more secure.
Please see as well:
PHP Syntax checking pre-source control
E_NOTICE ?== E_DEBUG, avoiding isset() and # with more sophisticated error_handler
isset() and empty() make code ugly
PHP defines two SPL exceptions for invalid keys:
OutOfRangeException: Exception thrown when an illegal index was requested. This represents errors that should be detected at compile time.
OutOfBoundsException: Exception thrown if a value is not a valid key. This represents errors that cannot be detected at compile time.
As PHP isn't a compiled language the distinction between compile-time and run-time seems strange and thus I am finding it hard to understand which exception to use when.
Currently my understanding is that one should throw...
... OutOfRangeException if the key is fundamentally and inherently malformed, e.g. if an array is passed as a key.
... OutOfBoundsException if the key is generally okay, but isn't in some boundaries, e.g. if 100 is passed but 50 is the maximum key.
Is that understanding correct?
While PHP doesn't have a classic "compile time" (or a compiler that do a lot of static checks for that matter) I'd treat "compile time" as "rather static stuff I did wrong when writing the code" and "run time" as "my logic, input or validation was off at some point".
So my suggestion would be to treat it like this:
"Compile Time" / "OutOfRangeException": The error can always be fixed in the source code without or with very little logic.
I always take numbers from 1-10 and you put in 11
"Run Time" / "OutOfBoundsException": The error is due to wrong use at runtime.
You created me and told me to take values from 1 to 5 then you put in 7. Doesn't compute
or
You request an index that is not there because you didn't put it there like you should
Sample:
I'd expect an SplFixedArray to throw an OutOfBoundsException because it's size is dynamic and can chance at runtime while I'd expect something like a Calender::getMonthName to throw and OutOfRangeException because the number of month are definitely fixed at "compile/write" time.
Array object sample:
Say $array is an object that implements ArrayAccess you could throw an OutOfBoundsException in these circumstances:
$array['bar'];
$array[7];
As the values are what you could expect for ArrayAccess but it doesn't make sense in the case of an SplFixedArray(5). Alternatives would be DomainException or maybe RangeException
An OutOfRangeException in these cases:
$calendar->getMonth(15);
As putting an array or a new class there is definitely some bigger logic flaw in the code that usually results from a simple "oh, i put in the wrong variable" error by a programmer. An (maybe preferable) alternative would be UnexpectedValueException and good old InvalidArgumentException.
For cases like:
$array[array()];
$array[new StdClass];
some of the alternative exceptions seem more fitting.
Comparisons with the Java world on which exception to use when are not always applicable as Java Developers have an additions issue to deal with.
Checked/Unchecked exceptions. With many people arguing that everything that isn't a runtime exception has very limited use in Java / should not be used much internally) those names have lost some of their original meaning and intent.
My own take on this is:
LogicException
use for any mistakes the developer did, e.g. mistakes when programming/assembling the application. Those will hopefully be catched when the developer is running his/her UnitTests (which would then be the equivalent of Compile Time). Those exceptions should never occur on the production site as they are errors in the software as such.
RuntimeException:
use for any mistakes the user did or that result from invalid data put in the application at runtime. These are errors that might be anticipatable but not fully preventable by UnitTests, e.g. those can happen on a production site. Those exceptions could be stemming from incorrect usage or programming errors.
OutOfBounds
is IMO effectively what Wikipedia defines as Range of an Array in Range in Computer Programming, namely:
When an array is numerically indexed, its range is the upper and lower bound of the array. Depending on the environment, a warning, a fatal error, or unpredictable behavior will occur if the program attempts to access an array element that is outside the range.
In other words, when you have an array with indices [0,1,2] anything but [0,1,2] is out of bounds. Note that Bounds can also apply to other data types as well, e.g. trying to access the 7th character in a 5 character string would also be OutOfBounds.
OutOfRange:
this one is a tough cookie. In C++ OutOfRange is a generic exception extending LogicException (just like in PHP). I am not sure if the example given is easily translatable to PHP code though or my definition of Compile time above. Mainly because no one would first init a new Vector(10) and the immediately try to access it at(20).
In Java OutOfRange seems to refer to Range in the mathematical sense
The range of a function is the possible y values of a function that result when we substitute all the possible x-values into the function.
One reference I could find has it extending RuntimeException though, so I guess looking into other languages wont help to solve this mystery. There is also an open bug report about the SPL Exceptions in general, stating that
OutOfRangeException (value is out of range) is LogicException, should be: RuntimeException
But if this is correct, then how is OutOfRange different from DomainException? And if your own definition is correct, then how is OutOfRange different from InvalidArgumentException?
To cut a long story short: I dont know what OutOfRangeException is supposed to be for.
The answer to your question is quite elusive to me also. However, here are some things to think about:
If an array is passed in when we are expecting a valid array key, we also have InvalidArgumentException because it is not the proper argument type.
We could also throw a DomainException because arrays are not in the domain for array keys.
In php, you generally can't detect types at compile time because of late static binding. They purposefully delay binding of variables to runtime.
How I handle this situation:
Throw an InvalidArgumentException if a variable is passed in to any function where it the argument is not the correct type. I still do this when working with arrays.
Throw an InvalidArgumentException if null was passed in when it shouldn't be. This one really could be a lot of things because null isn't typed. To keep error code checking simple, I simply stick with the invalid argument.
Throw OutOfBoundsException when an index is not in the correct range, just as you suggested.
Throw BadFunctionCallException if a user-supplied function as a parameter does not have the correct form. If your structure inside is an array, it makes sense that they could pass in a function to modify it, so this comes up occasionally.
Generally, I can use just these three exceptions to represent all errors that occur outside of special resources (Network and database connections would be special resources). The third one seems to have been cropping up more often, but primarily I've just dealt with the former two.
It is quite simple:
OutOfRange mean "Your requested key is not within the index of a set defined in code."
OutOfBounds means "Your requested key is not within the index of a set defined by loaded configuration."
The confusion in this case comes from a couple of factors. First, PHP is in fact compiled into bytecode. There are several execution environments where this compiled form persists in a relatively permanent form on the server. However, the OutOfRangeException/OutOfBoundsException issue is not about that, it's about a categorization error made by the people who documented these specific exception classes.
Since PHP is dynamically typed, it's often impossible to actually check ranges and even types at compile time. The manual states that OutOfRangeException should be raised at compile time and OutOfBoundsException should apply at runtime, which is an erroneous distinction to make in this context.
Both manual entries use unclear language of what an illegal index means, but looking at the usage of their parent classes gives some clues: LogicExceptions are extended by classes like DomainException, InvalidArgumentException, and LengthException, whereas Runtime exceptions are things such as UnexpectedValueException, OverflowException and UnderflowException. From this pattern one can infer that OutOfRangeException should probably be applied to illegal key types, and OutOfBoundsException should apply to index values that are of the correct type but are not within the bounds of their container.
There was some discussion on the PHP dev list about these categorizations being wrong, but the issue goes deeper than that. In practice, both exceptions can only actually be are raised at runtime. You can use the vagaries of the documentation to squeeze out a distinction between invalid key types and invalid index values, but at this point we're talking about a bug in the PHP documentation.
If you get an unexpected index. ie you expect a string but end up with an integer or vice versa. Then you should throw an UnexpectedValueException exception.
If you get a proper type of index but it doesn't exist. Then raise a warning (trigger_error) and proceed on. This is not expected to stop programming flow.
If you have an object that is iterable or supposed to be iterated over a range and it reaches it's limit (ie the end of a file), then you should throw an OutOfBoundsException.
Anything else is a candidate for OutOfRangeException.
In layman's terms. An OutOfBoundsException is something normal. It's not that serious. It's something that happens often and should be taken care of. it can be used by iterators to keep reading data till there is no more to read. It is a logical error. Made by someone using the code not by someone writing the code.
An OutOfRangeException is something serious. Someone should look at the source code. Someone should find out what happened. This is important. Theoretically this was never supposed to happen. Call 911. It is a compile time error. Made by the dummy programmer.
Out of range exceptions are written by programmers to guard against mistakes by other programmers. Or maybe yourself in the future. If you feel like something like that could never happen then use Out Of Range. Use Out of Bounds for something likely to happen.
i've set up all my php stuff on a new machine and i'm getting really lots of notices warnings.
my code is working properly without errors on my old machine.
eg. the following line (which should get a recordset value) will cause a notice:
$ID = $rs[id];
the reason is the missing quotes for the id fields, but also things like calling $_GET on a non-existing value will cause notices.
anyone knows what's the reason for this?
i'd love keeping the "simple" way of coding like on my old machine without having to hassle with quotes on recordsets or tons of isset() - any ideas?
thanks
The PHP installation in the new machine has a more robust configuration that shows notices, and not only errors. That's good. I would never write or accept in my server a PHP script that fires some notice.
This kind of "lazy" coding (forgive me, I want to help you!) brings to future issues (code is hard to read and to debug) and, indirectly, security concerns ("lazy" code is often flawed). Fix everything that fires up a notice. :)
And, if you can, learn some more advanced PHP: go for object-oriented programming, encapsulation, information hiding, etc... This is how things are done nowadays and they work better than before. Old PHP scripts, built around notice suppression and register_globals, were somewhat dump.
The reason for the notice is because you have an "undefined constant." If you do not put quotes around an intended string, php will treat it as a constant. If it's not defined, php treats it as a strong. Take the following example:
$array = array(
'one' => 'right'
, 'two' => 'wrong'
);
define('one', 'two');
echo $array[one]; //echoes "wrong"
Also, you will get a notice if you try to access a key in an array that is not defined (such as $array['three']; above). PHP is nice enough to do this for you as other languages will error out (or worse).
The notices are not just to bug you. They are to let you know there's a problem in your code that you should strongly consider addressing.
Sounds like your error reporting level differs between machines. Compare the error_reporting levels in your php.ini's across machines.
It sounds like you have a different error_reporting value set on the two servers. Check your php.ini and set accordingly.
The "goto" statement comes straight out of ASM or any other assembler language.
Here's a link: http://be2.php.net/manual/en/control-structures.goto.php
I'm wondering: what can this do to make my code more well-organized? How can I implement this in larger projects, without screwing it up.
Since the goto will allow you to jump back and forth, accidental assignments and infinite loops are waiting to happen if you use this the wrong way.
Can someone give me an example of a good use of this?
EDIT: allright, I've seen some of the replies and apparently a wide consensus exists about the use of the "goto" statement and it being bad.
So I'm still wondering: why would PHP bother to add it to the language. If they didn't see something in it, they wouldn't do it... so why?
Also: A discussion here on StackOverflow about "goto" in general
EDIT2: Seeing as this question induced a lot of bad things to be sad about the goto statement, I went and asked my father. He's 52 years old and is an Industrial Engineer. He told me a couple of times he did a good amount of programming in his days and mostly in FORTRAN and COBOL. Nowadays he does IT services, server&networkmanagment and such.
Anyways, he said some stuff about "back in my day..."
After discussing that a bit, he came back to the goto statement, saying that even back in his days as a student, they allready knew it wasn't a smart idea to use it, but they didn't have much better back then. Try/catch was still years away and error handling hardly excisted.
So what did you do to check your program? Add a few lines at the end that allow you to print output and everything you need to check in your code, and then you place the line: "goto printing;", or something like that, to start the printing of your data.
And in this manner, you gradually debugged your code.
He agrees that the use of goto in the modern programming world is pretty useless. The only use he finds justified is an "emergency break", to be used in extreme debugging and unexpected situations. Kinda like goto fatal_error;, and have the "fatal_error" part of your code do some things to show you in-depth results.But only during the creation of something. A finished product should not have goto-statements.
LATE EDIT: Another discussion about "goto" in PHP5.3/PHP6
If you're writing good PHP code, you shouldn't need to use goto. I think it's a mistake that they're adding it in, as it just leads to lazy programming.
See
http://www.procata.com/blog/archives/2004/07/29/goto-in-php/
For a good commentary on the addition of this to PHP, and also, here on stack overflow,
GOTO still considered harmful?
I have only ever found two uses for goto:
To break out of nested loops. But most newer languages have a mechanism to do this without goto anyway (break <number> in PHP, or break <loop label> in Java, etc.).
To go to a cleanup section at the end of a function. But again, this isn't often useful in a garbage-collected language.
In other words, if you don't know whether you should use goto for something, you shouldn't.
The main use I see in having gotos in a language is the ability to port across languages. I wrote a parser generator in C that generated parsers with gotos (because it was easier to use gotos than to implement more sane control structures), and now porting it to PHP isn't as much of a headache.
goto can help reduce code duplication for stack unwinding, in pseudo code below:
do A
if (error)
goto out_a;
do B
if (error)
goto out_b;
do C
if (error)
goto out_c;
goto out;
out_c:
undo C
out_b:
undo B:
out_a:
undo A
out:
return ret;
( Pseudo code by Robert Love, taken from the linux kernel archive mailing list: https://lkml.org/lkml/2003/1/12/203 )
It can be used for debugging purposes so you don't have to comment out or refactor blocks of code just to temporary change the workflow.
In Classic VB coding, use of goto is handy for emulating try/catch error handling like this:
Function MyFunction() as String
'-- start of error block
'
On Error Goto Catch
' do something here that might cause an error
MyFunction = "IT WORKED"
Exit Function
Catch:
' error occured - do something else
MyFunction = Err.Description
'
'-- end of error block
End Function
... and here is a way to emulate the try/catch/finally ..
Function MyFunction() as String
'-- start of error block
'
On Error Goto Catch
' do something here that might cause an error
MyFunction = "IT WORKED"
Goto Finally
Catch:
' error occured - do something else
MyFunction = Err.Description
Err.Clear
Finally:
' put your finally code here
'
'-- end of error block
End Function
It can also be useful for cleanup at the end of a function, although i suppose you could make a case that another function can be called to do that cleanup.
In all honesty, I have never had an occasion in PHP where I thought to myself 'hmm, I wish there was a goto statement'. I haven't read up on why they decided to do this, but, those guys are pretty smart, and have taken PHP into very good directions so far, so maybe the are anticipating a need that we don't realize yet.
There is no such thing as good use of goto.
Maybe, just maybe, it could be useful to get out of multiple nested loops, but you can already do that using "break 2" and such. Labeled breaks like in Java would be better than goto for this purpose.
Perhaps it's also useful with code written without using exceptions, when you need to skip to the end of a bunch of statements once one fails. But that's only fixing crappy code with more crappy code.
I admit I have never used goto in my codes. :)
The only reason for me seems to facilitate the shortest migration route from other languages to PHP (practically only changing the language without touching the control structures) and refactor the code on the 2nd stage of the porting.
Personally I believe in educated colleagues and as they can avoid the conditional break-s from loops, they would be able to resist the temptation of goto.
Goto is primarily used when writing finite state machines. When parsing context free grammer you will actually need one of those. Though we could live without goto if continue $case; is a valid statement within a switch block to jump to a different case and off course having case ranges as many languages nowadays have. Until then we are pretty much stuck with goto.
Sometimes I use goto to avoid multiple nested ifs. That's not only about the logic, the structure or the program flow, sometimes it can be just about how the code looks like.
Generated code could make good use of goto, I guess. The good thing about generated code is that you don't need to maintain it - you just regenerate it.
goto should really be something though that was in the language and would be being made obsolete due to better programming practises. Adding it now does seem like a backwards step.
The b big advantage of gotos is learning curve. One wonders why tools like visual studia and macs do well. The reason is that people want more than a great product; they want a
great product that they can learn to use in just an hour or so. Many programmers now
a days only program as one of their jobs. I see so many books say that one should never
use a goto and then give five or so technologies such that they say eliminate every
need of it. I say that just that fact that they mentioned 5 is proof of how good the goto
is!!!!! I don't have time to teach five things that include exception structures that
take whole chapters to explain!!!!! when all you really need is a simple goto that
can be explained in 30 seconds. Sure, you can create bad code with them if the
programmer wants--- but hey, most programmers don't want to write bad code and if they
did they could anyway. Most gotos in our lab made the code extremely simple to
understand and learn; much more so than reading a 2000 page book.
GOTO, the restricted execution control structure, can be used in the place of loops, but that is highly discouraged. Its use tends to encourage the creation of unstructured code, which is a terrible practice. It is most likely best if used only in development, for debugging (skip large amounts of code to access a particular problem area) and testing. The only other purpose for the GOTO is possibly for writing an assembler; not likely. GOTO, if used outside of development, should be used sparingly and only as a last resort. If possible, replace a GOTO with an applicable loop structure.
As for the thread linked last (GOTO command in PHP?):
As stated by Ishmaeel (edited by Gordon; by far the best answer):
The GOTO is simply an extended BREAK, with the ability to "use static labels".
"Basically, it will be enhancing the ability to break out of nested if statements."
The short answer is goto is a workaround for a limited stack space with much better performance in single threaded code. Other than addressing stack space or performance, its usage would be at least unnecessary and at most inappropriate because it causes unneeded complexity.
In over 2 million lines of code I've written in all languages, excluding machine code :-). Only twice has its use been necessary and both due to inspecting\sorting large tree datasets.
As has been said before, goto is only really required in some types of algorithms, usually those that come up in language parsing or finite state machines. I have never missed the lack of goto in PHP.
OTOH, I have programmed in a language where the only two structures were functions and conditional gotos: SNOBOL4. Since the risk of spaghetti code was so high, most SNOBOL4 programmers were/are careful to avoid that. But gotos did enable some very tight programming, creative loop executions and so on. It's actually somewhat easier to do FSM-type loops if all you have are gotos.