When to use procedural code in PHP
- All PHP scripts have to start with procedural code! Typically
you have an 'index.php' file as the entry point to your application,
and before you can use any objects, you have to instantiate them,
and the first instantiation has to be done procedurally - there is
no other option.
- In most cases there are certain 'bootstrap' tasks that have
to be carried out before you can process a request. This might
include registering an autoload function, setting up error handling,
and checking that the system is capable of running your application.
All of this is typically done procedurally (perhaps also using
static classes) because it is impractical to do it using OOP (for
example, if you do not control the deployment environment, you might
want your app to die gracefully even if someone tries to run it on
PHP 4 - but if you try to use OO features from PHP 5, it will not be
possible to die gracefully).
- You could use procedural code to provide alternatives or
additions to the built-in PHP functions (although you should first consider whether OOP would be better). For example, your script
might or might not have access to multibyte string functions - it
could be useful to have your own alternative functions that use
multibyte functions if available or the standard PHP functions if
not (you can use namespaces to override default PHP
functions in PHP 5.3 and above, but this might not be very wise as your code will no longer behave in the way it would be expected to behave by any other PHP developer! Better to write separate functions with a different name).
- If you are just writing an example script, a proof of concept, or a very simple script or plugin, there is probably no need to go OO.
- If you prefer to write procedurally and feel you write better code that way, there is no reason why you shouldn't do so! Procedural code is not 'wrong' per se, there is just a tendency for it to lead to code that is difficult to test and difficult to maintain. But some great applications have been written procedurally, and it can be an acceptable choice, especially if you don't need to collaborate with anyone else. Better to write good procedural code than bad object oriented code!
When not to use procedural code in PHP
- Pretty much any other time! Of course, I might not have
thought of everything, so there are probably other occasions when
procedural code is the right choice.