PHP ''Tutorials'' - Flow Design 
PHP Tutorial Index

Flow Design


One thing I struggled with for a long time when tinkering with programming was a good way to control the flow of my scripts. For years I stumbled around making uneccessary variables to check if data was alright or if functions succeeded. Until one day I noticed some code someone posted on a forum that showed something like:

if ($functionResult = some_function($paramValue))
{
// code to continue with
if ($newData = some_other_function($functionResult))
{
// and so on...
}
else
print('Could not get new data from some_other_function()<br/>');
}
else
print('Could not get a function result from some_function()<br/>');

To explain the above code... most functions in PHP will return a value of some sort, otherwise they will return something that will be handled as "false". Either a false value or a zero value. Any other value usually means "true" or - that the function worked as expected.

Suddenly something clicked in my head and I thought "why didn't I think of this before?". By using this method, you can execute the functions you need to do the task you are building but you are also verifying the execution of your functions.

Additionally, using an else { } statement lets you handle a failure. Depending on the nature of the function and it's dependency for the task, you may output a warning, error or kill the script with a die() message. This is not as sophisticated as real error handling can get, but it is a useful approach for novice/hobby programmers or web scripters.

PHP Tutorial Index