A function encapsulates a bunch of actions. Eg:
Code: Select all
<?php
function printR(&$array)
{
echo '<pre>';
print_r($array);
echo '</pre>';
}
?>
This could be convenient for basic debugging, if you need to check the values in an array/object. In a script, just type:
Fns create "chapters" in the script: ie a single fn call can replace several lines of "bare" code and so the script becomes much easier to read.
Choice of function names are important in this respect. For example something like:
Code: Select all
<?php
if(isModerator())
{
displayMovePostButton();
}
?>
.. is easy to understand (if just a touch too verbose - always better to err on the side of clarity though).
Always watch out for repeated code and try to encapsulate it in a function or object if you can. For example:
Code: Select all
<?php
function dbConnect()
{
$db_connection = @mysql_connect(DB_SERVER, DB_USERNAME, DB_PASS);
if ($db_connection === false)
{
#die ('Error: could not connect to server.<br />');
die('DEV ONLY: ' . mysql_errno() . ' - ' . mysql_error());
}
if (@mysql_select_db(DATABASE, $db_connection) === false)
{
#die('Cannot find database.<br />');
die('DEV ONLY: ' . mysql_errno() . ' - ' . mysql_error());
}
return $db_connection;
}
?>
Notice that, if you wish to change the error reporting level, you just need to edit one function def rather than many scripts throughout the site (swap the commented/uncommented lines around). This is one of the main benefits of encapsulation.
Fns can also encapsulate a repeated "pattern" such as looping through a db query to build table rows (products and creators are objects; I don't like Smarty):
Code: Select all
<?php
function stuffSmarty($product_name, &$creator)
{
$html = '';
$creator->i = 0;
$product =& new $product_name($creator);
while ($result = mysql_fetch_assoc($creator->getProductQuery()))
{
$product->nextRow($result);
$html .= $product->getHtml(); // return a complete html string eg a product post within creator topic
$creator->i++;
}
return $html;
}
?>
Kind of abstract: but that's the whole point. The same function can be used to build posts in a forum, topics in a board, or what have you. It's got issues but maybe illustrates the point.
Functions have their own variable scope. It's best practice to reduce variable scope as much as possible since that makes code easier to debug (fewer parts of the script might influence a var's value). Without fns, everything exists in the global scope. There are potential security issues with this (if have uninitialised vars & register globals on).
You might want to customise the behaviour of a native php fn for some reason. For example, count() can produce misleading results (try count($array) where $array === false). This is more robust:
Code: Select all
<?php
function cleverCount($array)
{
if(isset($array) and is_array($array) and count($array) != 0)
{
return count($array);
} else {
return false;
}
}
?>
Keep fns short and sharp: 6-7 lines is usually ample. Every fn should do just one thing.
I'd pay good money if all php'ers would organise spaghetti code into fns. It's often difficult to hunt down the problem in a posted script - probably the problem wouldn't even have arisen in better-organised code. If it's easier to read, it's less likely mistakes will be made.
Pretty much all the above applies to objects. OOP is all about making things simple. Once again, a whole bunch of stuff is encapsulated - this time behind a class interface. For example, I've been working all day on a set of form validation classes which (hopefully) will handle any shape or colour of form. The interface will provide just what I need to know, hiding the actual mechanics (this isn't functioning code just showing some of the public methods):
Code: Select all
<?php
$validator->matchKeys(); // returns true or false
$validator->getVar($key); // "firewall": returns validated value or null if it failed to validate
$validator->errorsExist(); // returns true (redisplay the form) or false (process submitted data)
?>
With OOP, just think of what sort of API you'd like, then go and write it. Find out more at phppatterns.com. Don't worry - it takes a while to sink in. First, get comfortable with functions.