PHP and MySQL Web Development - Chapter 5
Modifying Existing Code
Waning: modifying existing code can be more difficult than writing new code
Why Reuse Code?
1. more consistent 2. reliable 3. maintainable 4. less effort 5. reduces costs
Naming Your Function
Function names should be short but descriptive/meaningful your function cannot have the same name as an existing function your function name can only contain letters, numbers and underscores your function name cannot begin with a number your function name cannot contain a dash your function cannot have the same name as any built-in function you can use the same name in different files but may cause confusion unlike other languages, PHP does not support function overloading
PHP Error Messages
PHP error messages are usually very useful - they tell you exactly in which file the error occurred, in which line of the script it occured and for example, the name of the name of an undefined function that you attempted to call this information should make it fairly easy to find and correct the problem
User-Defined PHP Functions
PHP has numerous builtin functions, however, the real power of a program language comes from being able to create your own functions declaring a function allows you to use your own code in the same way as the built-in functions - you can call and reuse the as many times as needed throughout your script
Reusing Code: With PHP
PHP provides two very simple, yet very useful, statements that allow you to reuse code 1. require(); 2. include(); using these statements, you can load a file into your PHP script and that file can contain anything you would normally have in a script (text, HTML tags, PHP functions, etc. ) these statements work similar to server-side includes in by webservers and #include in C or C++ example: <? php require('page.php'); ?>
isset(); Function
a built-in function that tells you whether a variable has been created and given a value !isset() means NOT isset()
Using Parameters
a parameter allows you to pass data into a function and get data created outside of the function user-defined functions can have multiple parameters and optional parameters optional values do not all need to be provide optional parameters are specified last you can provide some and ignore some; keep in mind that you cannot leave out one optional parameter but include a later listed one - this is a common cause of programming errors (and why optional parameters are provided last) parameters are assigned from left to right
Anonymous Functions
also known as closures - are functions without names they are most commonly used as call backs - that is, as functions that are passed to other functions variables can also be used to hold a closure
Case and Function Names
calls to functions are not case sensitive - you are free to capitalize in anyway you find easy to read but you should aim to be consistent and use the same capitalization as used in the function definition important: variable names ARE case sensitive
Function Declaration
creates or 'declares' a new function it begins with the keyword function, provides the function name and parameters required and contains code that will be executed each time the function is called while built-in functions are available to all PHP scripts, functions you declare are available only to the script(s) in which they were declared it is a good idea to have a file/set of files containing your functions - you can then use a require() statement in your functions available where needed!
Changing Configuration Options (Apache)
first, your server has to be set up to allow its main configuration files to be overridden to set up auto prepending and appending for a directory, create a file called .htaccess in the directory and include the following two lines: php_value auto_prepend_file "/path/to/header.php" php_value auto_append_file "/path/to/footer.php" this syntax is slightly different from the same option in php.ini another of other php.ini configuration settings can be altered this way, too
Functions
formally, a function is a self-contained module of code that prescribes a calling interface, performs some task and optionally returns a result functions exist in most program languages they contain code that performs a single, well-defined task and can be used over and over this makes code easier to read
Basic Function Structure
function my_function() { echo ' My Function was called'; } and you can call this new function with my_function(); and will display the text My Function was called curly braces encode the code that performs the task you quire and between the braces you can have anything that is legal elsewhere in a PHP script including: function calls, new variable declarations, new functions, require() statements, plain HTML, etc
Reusing Code: Reliability
if code exists somewhere in your organization, it's likely that it has been tested if you attempt to re-write it, you may overlook something that the original author incorporated or something that was added after a bug was found during testing existing, mature code is generally more reliable than fresh, "green" code; with the exception of code old enough to be considered legacy code (outdated)
Reusing Code: Cost
if you are writing commercial code, you should attempt to limit the number of lines in use within the organization less code means lower costs and reusing code means less code to write if existing software meets the requirements of a new project, use it. the cost of using existing software is almost always less than the cost of developing an equivalent product
Calling an Undefined Function
if you attempt to call a function that does not exist, you will of course get an error message
Passing by Reference
if you need to alter a value, you pass by reference when a parameter is passed to a function, instead of creating a new variable, the function receives a reference to the original variable this reference has a variable name, beginning with the dollar sign ($) and can be used in exactly the same way as another variable - except that instead of having its own value, it refers to the original any modifications made to the reference also affect the original you specify that a parameter is to use pass by reference by placing an ampersand (&) before the parameter name in the function's definition - no change is required in the function call
Trying to Resolve an Error Message
let's assume you received the following error message: Fatal error: Call to undefined function function_name() in /path/to/your/file.php Start by checking the following: - is the function name spelled correctly? - does the function exist in the version of php you are using? - is the function part of an extension you do not have installed/enabled? - is the function in a file you have not included? - is the function in the scope? if you can not identify the problem, searching Google for the error code may be helpful
Function Parameters
most functions, require one or more parameters you pass parameters by placing data or the name of a variable holding data, inside parentheses after the function name function_name('parameter'); this again, calls a function named function_name but this time, it passes it a parameter (in this case, a string containing the word 'parameter') examples: function_name(2); function_name(7.993); function_name($someVariable); $someVariable might be any type of PHP variable including an array or an object - or even another function
PHP Variable Scope: Variable Scope
variables declared outside functions are in scope from the statement in which they are declared to the end of the file but NOT INSIDE FUNCTIONS these variables are called global variables
PHP Variable Scope: require() and include()
require() and include() statements do not affect scope if the statement is used within a function - function scope applies if it not inside a function - global scope applies note: no mechanism exists for explicitly passing variables to a required or included files
require() and Filename Extensions
require() handles filename extensions and PHP tags differently PHP does not look at the filename extension on the required file - this means you can name your file whatever you choose as long as you do not plan to call it directly require() will process PHP inside of an .html page and you can use any extension you prefer for include files but sticking to .php is a recommended if files ending in .inc or some other nonstandard extension are stored in the web document tree and users directly load them in the browser, they will be able to see the code in plan text, including any passwords
require() and Website Templates
require() is useful for creating a consistent look and feel throughout your company's web pages instead of adding elements and styles individually across dozens (or possibly hundreds or thousands of pages as the website grows), require() allows you to add common/reoccuring elements across those pages while only having to make changes to one file sections of your site can also be split across different files such as header.php, navigation.php and footer.php - then placed in their desired location with separate require() statements
Variations of require() and include()
require_once() and include_once() the purpose of these constructs is to ensure that an included file can be included only once this functionality becomes useful when you begin using require() and include() to include libraries of functions using these constructs protects you from accidentally including the same function library twice, thus redefining functions and causing an error if you are cautious in your coding practices, you are better off using require() or include() as these execute faster
Setting Options in the .htacess: Pro
setting options in the .htaccess rather than modifying your php.ini or web server's configuration file gives you a lot of flexibility you can alter settings on a shared machine that affect only your directories you do not need to restart the web server you do not need administrator access
PHP Variable Scope: Superglobal
special variables that are visible inside and outside functions the keyword global can be used to manually specify that a variable defined or used within a function will have global scope
Recursive Functions
supported in PHP a recursive function is one that calls itself, these functions are particularly useful for navigating dynamic data structures such as linked lists and tree few web-based applications require a data structure of this complexity it is possible to use recursion instead of iteration in many cases because both of these processes allow you to do something repetively recursive functions are slower and use more memory than iteration - you should use iteration whenever possible each call to the function makes to itself a new copy of the function code in memory; it's like 'pretending' that you are calling a different function each time although recursion appears more elegant, programmers often forget to supply a termination condition for the recursion - this means that the function will recur until the server runs out of memory or until the maximum execution time is exceeded, whichever comes first
return Keyword
the keyword return stops the executiof a function when a function ends either because all statements have been executed or the keyword return is used - execution returns to the statement after the function call an error condition is a common reason to use a return statement to stop execution of a function before the end exiting from a function isn't the only reason to use return - many functions use return statements to communicate with the code that called them and return a value functions that perform some task but do not need to return a value often return true or false to indicate whether they succeeded or failed
Calling Functions
the simplest call to a function is: function_name(); this line calls a function named function_name that does not require parameters; this line of code ignores any value that might be returned by this function
Require() vs Include()
the two statements are almost identical the only difference between them is that when they fail, the require() construct gives a fatal error, whereas the include() construct gives only a warning
auto_prepend_file and auto_append_file
two configuration options in the php.ini an alternative if you want to use require() or include() to add your header and footer to every page by setting these options to point to the header and footer files, you ensure that they will be loaded before and after every page and will behave as though they were added using an include() statement
readfile()
used if you want to be sure that file will be treated as plain text or HTML and not have any PHP executed this function echoes out the content of a file without parsing it this can be an important safety precaution if you are using user-provided text
Variable Scope
variable scope controls where the variable is visible and usable different languages have different rules that set the scope of variables
unset()
variables can be manually deleted by calling unset($variable_name) a variable is no longer in scope if it has been unset
PHP Variable Scope: Function Scope
variables declared inside a function are in scope from the statement in which they are declared to the closing brace at the end of the function these variables are called local variables it is perfectly legal to re-use a variable names inside and outside of a function without interference between the two - this is not recommended as it may cause confusion
Passing by Value
when you pass a parameter, a new variable is created containing the value passed in - it is a copy of the original and you can freely modify this value BUT the value of the original variable outside of the function remains unchanged
Setting Options in the .htacess: Con
with the .htaccess method, files are read and parsed each time a file in that directory is requested rather than just once at startup, so there is a performance penalty
Variable Number of Parameters
you can also declare functions that accept a variable number of parameters you can find out how many parameters have been passed and what their values are with the help of three functions: func_num_args(); func_get_arg(); func_get_args(); example: function my_function() { echo 'Number of parameters: '; echo func_num_args(); echo '<br />'; $args = func_get_args(); foreach ($args as $arg) { echo $arg . ' <br />'; } } this function reports the number of parameters passed to it and prints out each of them; the func_get_args() function returns the number of arguments passed in; the func_get_args() function returns an array of the argument alternatively, you can access the arguments one at time using the func_get_arg() function, passing it the argument number you want to access arguments are number starting from zero } this function
Reusing Code: Consistency
your software, system or program should be consistent, writing new code consistent with the way other parts of the system takes will and deliberate effort