PHP and the goto statement to be added in PHP 5.3 - php

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.

Related

If I declare(ticks=1) but don't register a tick function, what sort of overhead does the resulting tick processing incur?

First of all - there seem to be many questions about the fundamentals of tick functionality, so I want to add the top user comment at php.net/declare to the pile for anyone looking for further information. I found it while digging around as I tried to figure out the following.
So, I'm working on writing a simple debug helper. I want to add function tracing and benchmarking - basically what tick functionality is perfect for.
Thing is, I want to enable and disable benchmarking depending on arbitrary conditions that occur during script processing. I'm not really looking for fixed debugging Ă  la scoped declare() { ... }.
What I'm looking to do is to put declare(); at the top of my script, and then register and unregister my debugging/benchmarking (tick) function as appropriate. Un/registration won't happen (too) often, so is efficient and reasonable.
But then I got curious: when I don't have a tick function registered... does the fact that I've run declare(ticks=1); have any effect on execution efficiency? Does it cause any extra processing to become permanently enabled anyway?
Analysis of PHP(7)'s source code shows that the answer is technically yes, but I'm not yet sure how.
The answer seems to be in zend_compile.c:8200: it appears this function defers compilation processing to the appropriate routines, then if ticks are enabled it additionally emits a ZEND_TICKS opcode into the opline via zend_emit_tick() in :2167. The opcode reference page for TICKS seems consistent with this conclusion; it shows an example disassembled opcode listing which has TICKS opcodes scattered throughout it, and I was wondering how they got in there until I discovered the above.
The ZEND_TICKS handler (in zend_vm_def.h:6859) seems to call zend_ticks_function(). This is mapped to ticks_function() in zend.c:754, which is in turn mapped to php_run_ticks() in main.2013. This is finally defined in php_ticks.c, where it's all of:
void php_run_ticks(int count)
{
zend_llist_apply_with_argument(
&PG(tick_functions),
(llist_apply_with_arg_func_t) php_tick_iterator,
&count
);
}
Huh. Not bad.
But here's the thing. If I declare(ticks=1);, the above dispatch is being run for literally every statement executed. That's... ouch. For long-running scripts containing high-iteration-count, tight processing loops, I'm wondering how badly that'll add up.
Problem is, I'm not even sure how to benchmark this. The only way I could envisage to do so would be to synthesize some PHP bytecode and then figure out a way to inject that directly into the PHP bytecode interpreter.
And that leads to my question: how much of a performance impact does this additional dispatch have, in practice? How can I quantify it?
Obviously the above investigation was performed on the canonical PHP.net interpreter. I haven't looked into how HHVM does this at all (yet), but I wouldn't at all mind learning how it handles it.

Using try catch in php instead of checking for permission

I read an interesting quote on a Python forum that it's "easier to ask for forgiveness than it is to ask for permission". I'm not too familiar with the language so I can't say whether this is garbage. From working with .NET, it is my understanding that a try catch is an expensive operation and should be there for exception cases only. Kind of like a safety net.
Is there any merit to this type of behaviour with php? As in, is it quicker to read from a file inside a try catch vs checking to see if the file can be found / read before performing the read operation. I can see how it makes the code easier to maintain, but what are the perfoance implications. Is it more of a waste to check when 99.9% of the time the check is pointless.
To the best of my knowledge, this is not a standard practice in PHP. This is, in large part, because most PHP builtins threw PHP errors -- not exceptions! -- prior to PHP 7.0. PHP errors could not be caught by PHP try/catch blocks, making it mandatory to use explicit checks for functions that could fail.
If your code needs to be compatible with PHP 5.6 or earlier, you can't use this convention. It may be worth experimenting with if you can mandate PHP 7.0 or later for your code, but I don't know what implications this may have for performance.
Try and catch by itself is truly quite expensive. Even when it is not used (i.e. no exception is generated), there is still some overhead that is "embedded" into the generated assembly. As for simple check whether the file exists and can be accessed, same thing happens: both of the things are system calls that are generally even more expensive. You should, however, also consider that the read operation on a file is a system call as well.
Now the question is narrowed down to what is more expensive: 2 system calls or 1 syscall with the exception handling. My assumption here (which I am somewhat confident about) is that the latter will be more expensive in case where the exception is actually being thrown, but faster in other cases. Since you've indicated that there will, in most cases, be no problems with accessing the files, it may be the case that you "should" use the exceptions. It is easier to deal with errors and does make the code a little bit more pretty (although it is arguable).
A little bit more on the code side of things: it totally depends on what your framework looks like now and what you want it to look like. You can, in fact, create a class that will deal with all this stuff in any of the two ways and they both will look clean (if done properly) and easily maintainable. If, however, you don't feel like keeping it in a separate class (or a separate file\function\universe), I would go for the exception handling.
Finally, as said before, the exception handling will generally be faster in you case, but ask yourself a question: How much of a problem is it? Do you perform the operation once per page access or do you do it multiple times? Will the page be accessed often or just once a day? How much of an impact will this create compared to all the other pages\algorithms that you have. There is a good concept know as 90/10 rule: 90% of the code is executed 10% of the time and vice versa. If this particular code is in these 90%, you shouldn't even worry about the performance as your concern should be the other 10% of the code. (You can read more about this here)
And one more thing: as noted by duskwuff, whatever is written here holds for PHP version >= 7.0

When to use Try Catch blocks

Ok, this might be a very noob question, but I find that PHP Documentation on that and several Internet Searches hasn't give me any idea about that.
When should I use try-catch blocks to improve my application?
I read someone saying that we should use try-catch blocks only to prevent fatal errors.
I read someone else saying that we should use it only on unexpected errors (wait what? unexpected? if they are unexpected errors how could I prevent them with try-catch? should I put all my application code inside a try block?).
Others simply say that try-catch blocks should be used everywhere because they can be also extended (extending the Exception class).
Finally someone says that PHP try-catch block are totally useless because they are very bad implemented. (On this I found a nice SO question about performance).
It seems to me that this topic is very strange and confused. Could someone lights me up?
It seems to me that this topic is very strange and confused. Could someone lights me up?
Definitely. I'm not a PHP user, but I might have a little insight after having worked with try/catch in ActionScript, Java, and JavaScript. Bear in mind though, that different languages and platforms encourage different uses for try/catch. That said...
The only times I'd recommend using try/catch is if you're using a native language function that
Can throw an error/exception
Does not give you any tools to detect whether you're about to do something stupid that would cause that error/exception. eg: In ActionScript, closing a loader that is not open will result in an error but the loader doesn't have an isOpen property to check so you're forced to wrap it in try/catch to silence an otherwise totally meaningless error.
The error/exception really is meaningless.
Let's take the examples you list and see how they square with that list.
I read someone saying that we should use try-catch blocks only to prevent fatal errors.
In the case of AS's loader.close() function, this is good advice. That's a fatal error, and all from an otherwise trivial misstep. On the other hand, virtually ALL errors in AS will bring your application to a halt. Would you then wrap them all in try/catch? Absolutely not! A "fatal error" is fatal for a reason. It means something terribly wrong has happened and for the application to continue on in a potentially "undefined" state is foolhardy. It's better to know an error happened and then fix it rather than just let it go.
I read someone else saying that we should use it only on unexpected errors
That's even worse. Those are presicely the errors you DON'T want to silence, because silencing them means that you're never going to find them. Maybe you're not swallowing them, though... maybe you're logging them. But why would you try/catch/log/continue as though nothing happened, allowing the program to run in a potentially dangerous and unexpected condition? Just let the error kick you in the teeth and then fix it. There's little more frustrating than trying to debug something that's wrong in a program that someone else wrote because they wrapped everything in a try/catch block and then neglected to log.
Others simply say that try-catch blocks should be used everywhere because they can be also extended (extending the Exception class).
There's potential merit to this if you're the one doing the throwing, and you're trying to alert yourself to an exceptional situation in your program... but why try/catch your own thrown error? Let it kick you in the teeth, then fix it so that you don't need to throw the error anymore.
Finally someone says that PHP try-catch block are totally useless because they are very bad implemented. (On this i find a nice SO question about performance).
Maybe so. I can't answer this one though.
So... this might be a bit of a religious question, and I'm certain people will disagree with me, but from my particular vantage point those are the lessons I've learned over the years about try/catch.
Different people will tell you different things. But this is what I think, specifically in the case of a web application.
Your whole page should be in a try/catch that displays an error message to the user. The error message shouldn't tell the user what happened in detail because thats a security concern. It should record information about the error into a log file.
The other case is where something could go wrong in the normal operation of affairs. PHP is not very exception happy so this may not happen very much. Basically, if you run into a function that throws an exception when it fails, you can catch the exception and do something else in that case.
In general, your question is like asking how you would use a hammer to improve the qualify of a house. Use exceptions to help you implement particular behaviors. Don't look for places to use exceptions.
I think it's simply a matter of preferences, but from my experiences, I'd encourage you to use them as much as possible.
In application we currently develop at work (using Zend Framework if it matters), we use one single try..catch block to catch all exceptions throughout the application which are shown to user as, for example, error 500s and exception is logged with more information to database. I, personally, love this approach in case of PHP application as exceptions are extendable and you can basically write whatever functionality you need.
I predominantly use Try/Catch around database calls...especially inputs, updates and deletes etc.
I sometimes use it around complex data processing with arrays and loops using dynamic data and arrays where there is a chance something might go wrong, ie: missing array elements or something (I normally check for stuff like that though).
I also use them around operations over which I don't have complete control such as importing data from an external or foreign data source where there could be problems with the data or accessing the source file.
I think what is meant by "Unexpected Errors" is where you can't prevent problems through good programming practices such as checking if a file exists before "including" it, Some problems you CAN anticipate so use good practices to prevent them. Don't just leave them to chance by wrapping them in a try/catch.
Use good programming practices instead as you should do everywhere. Don't use try/catch as a lazy shortcut for everything, everywhere. That's major overkill.
I agree with #scriptocalypse. In fact I only use try/catch blocks in PHP in 2 kind of situations.
If it's possible that some external (not inside my code) issues or DB errors may take place:
Getting data from another source (eg. curl)
Getting data from files
DB-Exceptions
If I work inside another system, like a CMS or similar and I want to override a certain behavior. For example I don't want an Exception being thrown but the exceptions message being returned to the view.
You cant put try catch blocks everywhere.
However during application testing, exceptions generated should alert you to places where you need try catches. This is one reason why you should run thorough testing of you application/code.
If you see a place where you think you need it, i would put one in.
EDIT: ok you CAN put them everywhere, but you need some sense as to where to put them in your code.
I normally put Try and Catch around areas in the code that have external forces acting on it that I have no control over. For example, Opening and reading external files.. you have no control that at some point in the reading of the file, the file becomes corrupted or something else happens that you can not control like the file server dc's or something

Where to position include/require statements?

Do you position all of your include_once and require_once at the start of the file, so it's clear what it's dependencies are, or do you put them at the most local scope where they are used, for efficiency?
Let's say I have an error handling file which has a function to display an error message - would you ...
require_once('error_handling.php');
... lots of code ...
if ($should_be_true === False)
{
ReportErrror(); // declared in error_handling.php
}
or do you
... lots of code ...
if ($should_be_true === False)
{
require_once('error_handling.php');
ReportErrror(); // declared in error_handling.php
}
hmm, looks like they deleted the best-practise tag, along with subjective in the great tag purge of '10
This is probably a matter of taste for the most part.
In C/C++ style, I always put them on top, so - as you mentioned - the dependencies are immediately clear. Also, it gives you the option to rearrange the order of inclusion (which should normally never matter).
Now, since this is a runtime affair (unlike C/C++), it would make sense to postpone including huge files that are rarely ever needed.
It's a matter of balance - cleaner code (IMHO) vs performance. I would tend towards cleaner code, unless you have a PHP file that is a) called a lot, b) uses a huge PHP file that is c) almost never needed.
I'd most definitely go with the second example, because to load in stuff that potentially wouldn't be used is just evil.
Meh. Totally dependent on the situation.
If it's a small include and you're going to use it in 95% of situations, top is fine. Top really is fine for almost all cases.
But if it's an absolutely huge library to, say, parse something that will only come up in 5% of requests, require when needed. It might be worth making a comment at the top to make the dependency known, however—happy medium?
Anyway. It's a judgment call every time. Best not worry too much about the performance issue for the uncertain cases until milliseconds of performance actually become an issue for you. (And wouldn't that sort of popularity be an excellent issue to have?)

write php code to mysql?

Is there any possibility to write php code to mysql and then use it in php, in order to process the output, not just write it?
I would like to use mysql, instead of included file...if it is possible.
You can use the eval() function to run a string as PHP code.
Store the string in the database and then get it from a query and run eval.
As everyone here will be saying, this isn't the best practice. There's a good chance that there is a better solution that you just haven't thought of yet. If there isn't, make sure the values in the database are not user editable of there could be some serious problems!
Alternatively, if you want to play it safer, you could define the PHP functions that can be called, and just store the function name. Then use call_user_func() to run the function!
This is much safer since you have explicitly defined the functions available to be run, but less flexible of course.
eval
Sure you can, you may use eval. But beware - eval is evil and if it contains user input a malicious user may take over your server. So, please, be kind, and don't use eval!
Yes you can store the PHP code like any other text and then use eval() to run it.
But: You won't get any warnings/errors if your code is wrong, only on runtime. This makes debugging your code extremely difficult.
So don't do it!
Really, I am serious about this. In the end, you will have a lot more work.
Besides that, without this database thing, your code is also easier to read and understand by others. They don't need to know what code is in the database, they can just look up the file that is included.
As others have answered, yes, that is possible; you can use eval() to run arbitrary PHP code. But it is rarely if ever a good idea to store PHP in the database and eval() it.
Perhaps you could outline what exactly you want to achieve and why you feel storing PHP in the database is a good solution. That way, if anyone feels he has a better solution for your problem, he can suggest it.
Sure it is possible and can be a good speed improvement. I'm using the cms "contenido" (www.contenido.org) where this practice is used for some editable components, (layouts/modules/data types etc.). Finally all code for one article is stored in one field and is performed with one eval call. Contenido is not perfect, nevertheless a good example for this practice.
Missing version control is a disadvantage. But it is not a real problem with a simple way to export and import the code fragments.
As everyone says it's a bad practice to store your code in database and use eval function. My personal reasons are:
I care about debugging (there are plugins for php that let you debug your php code. PHP debugger is integrated in PhpEd and I believe it is integrated in NetBeans too) and it would be more difficult with eval.
Performance issues:
The speed of eval Besides security
concerns eval also has the problem of
being incredibly slow. In my testing
on PHP 4.3.10 its 10 times slower then
normal code and 28 times slower on PHP
5.1 beta1.
(Source: http://blog.joshuaeichorn.com/archives/2005/08/01/using-eval-in-php/)
EDIT: Here are my results from testing script above on my machine (PHP 5.3.0):
Eval: 1000000 times took 8.2261250019073n
Same code not eval: 1000000 times took 0.27089691162109n
Eval in function: 1000000 times took 0.8873131275177n
So "evaled" code is 30.4 times slower than not evaled version of the same code.

Categories