Software Development Planning

Introduction

Writing High-Quality Code
High-quality code is code that works well, works efficiently, is well documented, is easy to debug and maintain, and is also easy for others to work with. But because there are many different ways to code applications and produce the same functionality, you may end up working with code that does the job, but is poorly written and therefore hard to maintain.
Establishing and following a formal development process can be a pain (especially if you're used to seat-of-the-pants programming), but it helps produce high-quality code and is essential for the success of larger projects. And although some differences in coding style are to be expected, and perhaps even encouraged, using a consistent approach (as defined by a coding standard) brings great benefits, especially when building larger projects within an organization. Using a coding standard, such as the ones discussed in this post, is a vital part of high-quality code.
Another gauge of high-quality code is how well it is structured. Functions and include files should be used whenever you are performing the same processing, or nearly the same, in multiple locations in your program, simply because using them means only having to modify the code in one place, rather than many. These indicators are among those discussed in this post that can guide you in writing first-rate code.
In Post you discovered how to make your code more graceful handling errors, more secure, and more efficient. In this post you continue along the path to quality code by learning about coding standards and the use of functions, objects, and include/require statements. You'll also review development processes and learn how to optimize your code. As you can tell, there's a lot of work involved in creating high-quality code, but you won't be sorry—it'll be well worth your effort.

Development Planning
The importance of planning is stressed throughout this book. Although not every job allows for a good deal of planning up front, it's always best to fight for the time to properly plan your applications. Once you've invested the effort to plan your application, coding it almost becomes a breeze.

Formal Software Development Processes
There are any number of formal software development processes you might use; all have certain features in common, such as writing a specification, developing testing protocols, and so forth. If you work for a company that builds software for the government, you may be required to adhere to a software development process defined by a standard, such as ISO 12207 (ISO stands for International Standards Organization). Or, perhaps your company uses a less formal approach such as Rapid Application Development, in which several developers share responsibility for rapidly creating and modifying the workings of an application.
Which ever development process is used, following formal procedures in a standard way increases the odds of successfully completing the project on time and within budget. As you can imagine, a scattershot approach is very inefficient, especially if there are multiple developers at work.
That said, it isn't unusual for even the most well-managed projects to have delays, changing specifications, mistakes, hard-to-find bugs, and so on. That just means that deciding upon and following a formal procedure is more important than ever.
The next few sections discuss some of the basic features that formal software development processes share.

Writing a Specification
Writing a specification is a great first step, but one that's often ignored or slighted because it is often difficult to accurately and completely define what the final product should be. If you've ever read about how movies are made, for example, you know that the finished product may bear little resemblance to the original book or screenplay. A movie may not follow the script exactly, but there is always a script—it'd be very hard to convince anyone to put up money to make a movie without a script.
How much specification writing should be used for various applications? Let me give you some analogies to photography or movie-making:
• Snapshot: Some applications are like amateur photography—an abrupt snapshot and that's it. Of course, the result you get is much like that quick photograph, but sometimes that's all you need. A minimal application, such as displaying the current date on a Web site, doesn't really require any written specification. Little thought is used in deciding its location, and certainly no heavy thinking is involved in writing the code.
• Portrait: Even small applications, if done competently, are more like professional photography. The lighting is good, the subject is framed properly, and the quality of the image is excellent. They cost a bit more in both money and time, but some thought is put into how the result looks onscreen, and the color, font, weight, and size of the text. The programming is commented correctly, with proper use of conventions (even for a very small application). One or two paragraphs of specification may be all that is needed to completely define what's required.
• Commercials: Commercials are much more expensive, professionally done, and scripted. They are akin to small but professionally designed applications for a specific use. Likely there is little improvisation in them, and it's pretty easy to predefine (and ensure during production) all aspects of the process so that the final product is very closely aligned with the original script and goals of the production. Applications such as an e-mail newsletter manager are similar in that they are fairly simple in design and architecture. A good specification can be created in advance of production, and can be followed to completion without much deviation.
• Movie: A movie is like a very complex application in that it even though it may be scripted from end to end, the final cut may be very different from what was originally specified. That's because many of the final decisions are made once filming is finished, and depend upon the reaction of the filmmakers to what they have on film. A complex application is similar because you often won't know what is good or bad (or unnecessary) about the application you've created until beta testers or users use it a bit. And as an expensive project, once you're committed to it, it deserves as much modification as needed to make it right (from the user's standpoint, making it right can be summed up as "it works").
The point of these analogies is that some projects don't require much (if any) specification, and others require lots, but even when a good specification is created prior to any coding, there's still likely to be much change and retooling as the application takes shape. And that leads directly into the next subject, the coding process.


The Coding Process
There's a school of thought that says, "If you program all the little functions independently, then put them together, you'll have a finished application." The idea is that, if you can define what each part is supposed to do, and program that, then you should be able to put all of the parts together and have a working application. This is true to a degree, but often what distinguishes a (technically) working application from a great application is how well integrated the parts are (how efficiently and elegantly they work together).
The ease with which other people grasp how to use the application is also very important. Because many applications are intended for use by people, and people have varying perceptions and understandings of words, images, forms, and so on, the design of user interfaces is actually more art than science.
Given that there are so many tools that make it easy to develop a working model of an application fast, it's no surprise that Rapid Application Design (RAD) and Extreme Programming are popular. There are several definitions of RAD, but basically it means quickly developing a user interface that does the required tasks, and exposing it to users early in the development cycle. This is a relatively inexpensive process, and because you repeat the process several times quickly, you can hone in on a user-friendly design in a very short time. Once you have a good feel for all the aspects that are needed to satisfy the basic goals of the application, you can then spend the effort to properly organize, document, and optimize your application.
Extreme Programming is similar to RAD, but generally means you use two programmers to write the code so that they can assist each other, fill in for each other if one must take a break (or leaves the company), and otherwise arrive at the solution much quicker. Extreme Programming puts into practice the notion that "two heads are better than one," with real results in many cases.

Testing, Debugging, and Maintenance
Ever hear of a program or application that stopped at version 1.0? A program that was designed so well that it's never needed a revision, change, update, bug fix, etc.? Of course, not. There aren't any! And for good reason. Not only do most applications have bugs even after they're released, there's really no end to bugs, only the prospect of getting them to be insignificant enough so that for most people, under most circumstances, the application works well.
In addition, the environment in which applications operate (including protocols, operating systems, and other applications) changes constantly. And sharp hackers continually find new and interesting ways to defeat security and crack applications. Finally, good users will provide comments about other features they'd like in the application.
The bottom line is that the cycle of testing, debugging, and improving applications doesn't really end, but the rate of fixes and changes drops to a manageable level and becomes maintenance. This portion of the development process can't be avoided, but there's always the capability to manage the process well.

Optimizing Your Code
Imagine for a moment that you have 1,000 Web pages, and that each needs to display the current date and today's welcome message. Knowing PHP, you immediately see that it would be less work to have the pages dynamically generate the date and a message via a line or two of PHP code than to manually update 1,000 pages every day.
But you also want some way to write the code once and insert it into all the pages dynamically, so that if you ever changed the message it would change across all the pages at once. And of course, this common problem is solved easily in a number of ways with PHP functions such as include and require.
Using PHP and other functions to save yourself work is one way to optimize your code. Optimization isn't limited to just reusing code; the word also describes many techniques you can use to make your code run faster and more efficiently (using less computational resources such as CPU cycles, RAM, or hard drive space), to avoid rewriting code, or to make your programs easier to debug or maintain.
The rest of this post focuses in detail on practices that can save you lots of time and make your code more robust as well. These practices include formal coding standards, writing program logic as functions, and using the require() and require_once() functions.


Using Coding Standards
Just about any programmer you ask will tell you that properly indenting code for branching (control-flow) code blocks makes the code much easier to read, and therefore easier to debug and maintain. But there are actually several ways to indent code, such as using the tab or using multiple spaces. Either technique results in indented code that is easier to read, but for the sake of consistency it's pretty clear that you should use the same technique throughout a project, especially when collaborating with other programmers. Like most folks, you'll probably pick up some habits that you stick with when writing code. There's nothing wrong with that, but you may find yourself required to change your habits if you move from a company that codes one way to a company that uses another way.
Any conventions about what techniques to use when writing your programs (that don't actually affect whether the code runs properly) can be classified as coding standards. These include documentation and comments, indenting, naming conventions, the format of function calls, how to include code residing in other files, and so on.
We discuss (and try to follow) the PHP Extension and Add-on Repository (PEAR) coding conventions in this book. Writing to these standards makes your code ready for the repository.

• Indenting: Use four spaces, no tabs. Some text editors allow you to set the Tab key so that it produces four spaces instead of a tab, and this setting may make your life easier if you're used to using the Tab key for indenting. The PEAR coding standard also recommends that you break lines at 75–85 characters, but there is no hard and fast rule on this.
• Naming conventions: The PEAR coding standard has conventions for naming everything from c lasses to functions to variables.
               o Classes:
                                Use descriptive names, start the name with an uppercase letter, and divide your classes into categories, with each category and subcategory name separated by an underscore (such as Cart_orderitem for an item ordered within the context of a shopping cart).
               o Functions and methods:
                                Use lowercase letters to start a function name, and studly caps for subsequent words in the name. For example, getData() is a good name for a method that retrieves data, and calcTax() is a good name for a function that calculates tax. (Although it's not the PEAR standard, you may use underscores between words in your function and method names as well: array_combine(), for example.)
               o You haven't encountered methods yet; they are like functions but exclusive to objects. You'll learn more about them later in the book, in the post that discuss objects.
               o Constants: Use all uppercase characters, with underscores separating the words in the name.
               o Global variables: Use an underscore to precede the name of the global variable.
               o Predefined values: Use lowercase letters for true, false, null.

• Formatting function calls: There's no space between the name of the function, the opening parenthesis, and the beginning of the arguments. Use one space after the comma separating each argument, like this:
• $somevariable = myFunction($arg1, $arg2, $arg3);
The PEAR coding standard also indicates that there should be spaces before and after the equals sign when a variable is set equal to the result of a function call. Putting spaces between operators at all times makes your code much easier to read and understand.
• Formatting control-flow structures: Use one space between the beginning of the statement and the condition, like so:
• if (this equals that) {
•    //do something;
• }
Always use curly braces, even if they are technically optional.
• Comments: Use a double slash (//) to comment lines of code, like this:
• //here is a comment

    Use / * and * / to comment blocks of code, like this:
/*
here are several lines of code
here are several lines of code
here are several lines of code
here are several lines of code
*/
Use PHPDoc standards (www.phpdoc.de) for writing inline comments about object classes.


• Including code: You'll learn the details about including (or requiring) files containing code (or content) later in this post. The PEAR coding standard indicates you should use require_once() to unconditionally include class files, and include_once to conditionally include class files.
• Delimiters: Use <?php to start and ?> to end PHP code blocks.
• Defining functions: When writing functions, place the name of the function and the definition of its arguments on one line, follow with a beginning brace, and after all other lines of code, end with a closing brace. This is called the "one true brace" convention. Also, place any arguments with default values at the end of the argument list in the function definition, and always make your functions return a meaningful value if they are supposed to return anything. Here is an example:
• function myFunction($arg1, $arg2 = '')
{
    if (this equals that) {
        do something;
    }
    return true;
}
Example URLs: Whenever you need to specify a fake URL (such as http://www.fake_url.com) use example. com, example. net, and so on, like this: http://www.example.com).

Writing User-Defined Functions in PHP
PHP contains quite a number of built-in functions, such as isset(), strlen(), and so on. And although built-in functions always accomplish very useful tasks, you can be sure that not every possible function can exist in any version of PHP, even in future versions. So suppose you need a function that doesn't exist in PHP. That's where user-defined functions come into the picture—essentially you have the capability to author your own functions, and make them do whatever you want!
Any functions that you create are called user-defined functions. You use the function keyword to define a function and, once defined, that function may be used anyplace in your code, simply by calling its name. When combined with the capability to include files, functions become a very powerful tool in your programming arsenal.
Functions enable you to encapsulate sections of code as though they were independent stand-alone programs. You can pass values into them, and get values out of them. You can call functions at any time during your PHP script, and redirect the flow of execution in this way.
Functions also introduce the idea of scope (fully discussed later in this post) into your programs. The normal process in your PHP programs is that once a variable is created, the name you have assigned to it, and the value, persist until you alter it or until the script ends. However, in functions you have to learn to deal with the idea that variables might only exist inside a function, whereas outside it they have no value.
In this post you'll build some functions that will work on the same principle as the readymade ones you've already used: when you supply them with information, they will perform an operation and return an answer.
The Structure of Functions
Functions are sections of code that are defined by the user to perform a specific task, and given a name by which to call them. You already know that functions can take values called arguments as input, perform some operations, and then may return another value. The function transfers any argument values into new variables called parameters, which can then be used within the function. You've used PHP's built-in functions extensively in this book so far; to do things like get the data type of a variable (gettype()) right through to sorting arrays (sort()). Writing your own function means you get to give it your own made-up name, but you call it the same way as calling the built-in functions.
Take a look at how functions work, step-by-step:

1. The function is written with a name followed by parentheses. Inside the parentheses are the names of any values the function accepts (these values, called arguments, are optional), written as variable names (preceded by a dollar sign like any normal variable) and separated by commas.
2. The function is called by writing its name and parentheses. If the function requires any arguments, they are included within the parentheses and are separated by commas. Arguments may be variables or hard-coded values, and do not have to be the same as the variable names in the argument list in the defined function.
3. When the function is called, arguments passed to it are turned into parameters, and the parameters are used inside the function to perform the data processing specified by the function. Think of parameters as placeholders for values being passed into the function.
4. The return keyword may be used to pass values back out to the calling code after data processing is complete inside the function. Returning values is optional; some functions just do their work and then end without any further notification required. However, it is a good idea to at least return a true or false value to indicate to the rest of your code whether the function successfully completed its work.
5. If a value is passed back out of the function, it can be expressed using the echo statement, or it can be assigned to a variable outside the function.

Switching Functions

In the same way that you can use the switch structure to switch among various processing options within a PHP program, you can write your own functions that accept incoming values and, based on those values, switch among various other functions for processing. This is a very powerful feature of user-defined functions in PHP.
Here's a quick example. Suppose you want to create an application that pulls records from various tables in a database. You might send an input value in a variable called $ table_name to the switching function, and within that function decide which query function to run, as shown in this code:
function query switch($table_name)
{
   switch ($table_name) {
      case "clients":
         $query = query__clients_gen());
            break;
      case "orders":
         $query = query_orders_gen());
            break;
      case "employees":
          $query = query_employees_gen()) ;
          break;
      default:
         echo "Please select a table name";
   }
}
function query_client_gen()
{
   //composes a database query to select records from the clients table
}
function query_orders_gen()
{
   //composes a database query to select records from the orders table
}
function query_employees_gen()
{
   //composes a database query to select records from the employees table
}
The beauty of using this type of structure is that you can place the functions you've written into an include file, and then include the functions in any page, making it easy to add the composition of database queries to any page you like. In addition, you only need to change the code once if you're making an improvement to it, and the code is easier to read through. In fact, once you're confident that the functions do what you intend, you don't really have to read through them as you're coding, you can just call them whenever you need them.
Because you can assign the result of a function (one that has a return value) directly to a variable, you can simply use the result of a function in a switch..case statement. For example, suppose you create a small management function that tells you how many hits occurred on a page. You can take the number of hits returned by the function and use it to echo out an easy-to-understand message to the user, as this code shows:
switch ($hit_counter = get_hits ($current_page)) {
   case $hit_counter <100:
      echo "Few hits today";
      break;
   case $hit_counter <1000:
      echo "Lots of hits today";
      break;
   case $hit_counter <:10000:
      echo "Too many hits today";
      break; }
The variable $hit_counter would then be able to store whatever the function get_hits($current_page) returned (where $current_page is set to the filename of the current page, and gets the total number of hits today from your hit tracking program). You can place and set the value of the $hit_counter variable right inside the brackets of the switch() statement.
As a utility, you could set this function within each page and have it run once each time the page is displayed. The user would immediately see an indication of the number of hits for that page (although some users might be tempted to keep refreshing the page to up the number of hits).

How Values Get Inside Functions
As discussed earlier, parameters are placeholders representing values passed into a function. But there is more than one way to get a value into a parameter so that the function can work on it. You can pass a value into a function by value or by reference. The difference is subtle, but sometimes very important.
When you pass a value into a function by value, you assign the value directly to a parameter. But when you pass a value into a function by reference, you connect the parameter directly to a variable outside the function, forcing the outside variable to adopt whatever value the parameter gets.
Passing Values by Value
All the functions you've seen so far passed values by value. A value is passed into the function by entering the value (literally, or by naming the variable containing the value) into the spot reserved for that value (the place within the parentheses following the function call).
For instance, in the first bonus example, you can pass in the total sales value by entering a number directly into the spot reserved for the argument, or you can simply set a variable equal to total sales and then enter the variable name into that spot.
The following code shows both methods of passing by value:
function bonus($total_sales)
{
   $bonus = $total_sales * 0.15;
   return $bonus;
}
$total_sales = 120499;
echo "Your bonus is " . bonus($total_sales);
echo "Your total sales were " . $total_sales;
echo "Your total sales were $120,499 and your bonus is " . bonus(120499);
Notice that even after the value of $total_sales is set outside the function and then passed inside the function for processing, the external value of $total_sales is not changed. No surprises here.

Passing Values by Reference

Passing values into a function by reference has a completely different effect. The external variable used to contain the value being passed into the function is actually changed while the value is being processed. It changes because, in fact, you're not passing a value into the function, you're passing a reference that points directly to the external function. It's as though all processing operations taking place inside the function are actually affecting the external variable directly.
How is it done? Put the ampersand (&) before the name of the argument to be passed by reference. Our next example shows this for the $salary argument.
So suppose you were adding a bonus to a variable called $salary. Obviously you could do that outside the function, but perhaps it would be a little easier and cleaner to do it inside the function. The following code shows how this could work:
function bonus($total_sales,&$salary)
{
   $bonus = $total_sales * 0.15;
   $salary = $salary + $bonus;
   return $salary;
}
$total_sales = 120499;
$salary = 40000;
bonus ($total_sales, $salary);
echo "Your salary, including your bonus is " . $salary;
echo "Your total sales were " . $total_sales;
In this case, you don't need to set any variable to the value resulting from calling the bonus() function; you set $ salary to 40,000, then pass it by reference into the bonus() function, and when the function is done, it passes the value directly back into the $salary variable by reference. Neat, eh!

Setting Default Parameter Values
Like many other programming and computer related things, you can write your functions to have default values. For example, you can define an argument as having a default value, which the parameter for that argument will adopt when the function is called, provided you don't pass a value in for that argument.
But there is one catch: you must define any arguments with default values to the right of any arguments without default values. This is a little odd, but if you don't write your functions that way, they won't work as you'd expect.
The following
example writes the bonus function with a default value of $40,000 for salary to the right of the argument for total_sales:
function bonus($total_sales, &$salary = 40000)
{
   $bonus = $total_sales * 0.15;
   $salary = $salary + $bonus;
    return $salary;
}
$total_sales = 120499;
bonus($total_sales);
echo "Your salary, including your bonus is " . $salary;
echo "Your total sales were " . $total_sales;
This means that if you supplied no $salary value to the function, it would automatically use 40000 to calculate with. But if you do pass a value (higher, lower, the same—it doesn't matter) to the function for salary, the function would use the passed value to calculate with.
Parameter Order Matters
When you call a PHP function, whether you wrote it or it's built-in, the order in which you pass argument values does matter. If you leave an argument(s) out at the end of the list of arguments, you can leave off the last comma separating arguments. Also, if you leave out an argument, the function will automatically assume a zero value for a numerical argument, or an empty string for a string argument (unless the function defines a default parameter value itself), and continue processing. You'll only get a warning or error message when a required argument (one without any default value set) is missing, but of course, the level of warning or error message you receive will depend on the version of PHP you're using and also possibly on the way you're set error reporting.


Scope of Variables

You can create variables in a PHP script both external to a function (outside the function) and internal to the function (inside the function). If you create a variable named $total_sales outside a function, for example, and then pass its value inside a function that performs processing on an internally created variable named $total_sales, you have two distinct variables named $total_sales in existence in your script.Obviously, this situation is not going to work unless the two variables stay separate. So PHP uses the concept of scope (like so many other languages), and differentiates between the two variables so it doesn't get mixed up.
If you think about it, there are many situations where it would be convenient to use variables with the same name in one script or program. Scope allows PHP to work with two variables of the same name, so long as they remain in their appropriate places. (In much the same way, namespaces provide a means for XML elements of the same name to work within the same XML document and still stay separate.
Variables created in a PHP script have a lifetime as well as scope. A variable created inside a function stays in existence only as long as the function is processing. When the function finishes, the variable is lost, unless you define it as a static variable (more on static variables a little later in the post). So you say the scope of the variable is inside the function, and the lifetime of the variable is as long as the function is performing its work (a new inside variable is created each time the function is called, and it has a new life). All variables in a PHP script reach the end of their lives when the script is done.

Global and Local Variables
Variables that are created outside a function remain alive until the script ends, and are therefore said to have global scope, meaning they can be accessed from anywhere in the script. However, to access them within a function, you must use the global keyword. Placing the keyword global before the name of a variable means that you can use it within the function (but you can't then create another variable of the same name because that name is now taken within the function as well). Variables that are created inside a function are described as having local scope.
Here's an example of how local and global variables work:
<?php
$global_message = "Global Message";
function addto_message($global_message)
{
   global $global_message;
   $global_message .= " And More";
   return $global_message;
}
addto_message ($global_message);
echo "the global messge is " . $global_message;
?>
This example produces a statement with the value "The global message is Global Message And More" because running the function changes the value of $global_message. It only changes because the global keyword is used; it's almost like passing the argument into the function by reference.
In fact, putting the global keyword in front of a variable name inside the function does reference a superglobal array variable named $_GLOBALS. In this case, creating the variable $global_message (or any variable, for that matter) in the PHP script outside the function (and thereby with global scope) automatically sets it as part of the $_GLOBALS variable. So there are really two ways to access global variables from inside a function: by preceding their names with the global keyword (like this: global $global_message), or by using $_GLOBALS superglobal array variable (like this: $_GLOBALS[global_message]).

Creating Static Function Variables
That creating a variable inside a function with the keyword static in front of it allows that variable to persist beyond the time the function runs. And because the static variable exists only in the local scope of the function, both the variable and its most recently accumulated value will be available next time the function runs. This can be useful anytime you want to count something that happens or is measured within the function.
For example, suppose you want to count the records returned each time records are retrieved from a database. You could write something like this:
<?php
function get_records($table)
{
   //make database connection
   //retrieve records
   //get_record_count
   static $record_count;
   //set $record_count equal to number of records returned, plus any current
   //value it holds
   echo "current total records retrieved is " . $record_count;
   //return something
}
Although the example is mostly pseudo code, it shows how to set the $record_count variable so that it is static. And it should be clear that each time the function runs (at least, as long as the PHP script is running), the $record_count variable will be incremented by the number of records returned. For example, if you retrieved 20 records the first time, 30 records the second time, and 40 records the last time the function was called within a PHP script, then $record_count would be set to 90 by the end of the script. Of course, you could echo out the current record count each time, as this example did.
Here's a quick recap of global, local, and static variables:
• Global variables have values that persist throughout the whole program, but to use them inside a function you have to prefix them with the keyword global or address them using the $_GLOBALS superglobal array.
• Local variables have values that exist only inside of a function and only for the duration of one function call.
• Static variables are local variables that persist in value inside the function every time the function is called.

Nesting
It's possible to create and call functions within functions. This is called nesting, but under most circumstances this capability isn't very useful. You've already looked at calling functions from within functions, and by itself this is helpful.
But to define and call a function inside a function can lead to problems.
For example, you could write a parent function that would, within itself, define another function (call it the child function). The problem is that if you call the parent function twice, you're in effect trying to define the child function twice, and you can't redefine existing functions, so the script would fail. Mostof the time you're better off just defining functions separately.
But there is another situation (besides using functions for switching, as discussed a few sections ago) when it would be useful to call a function from inside a function: recursion (a function calling itself).

Recursion
Calling a function from within itself is known as recursion. Calling a function recursively creates a looping structure, in that the function will continue to call itself until a condition is met. However, you have to create the condition explicitly within the lines of code in the function, and if you don't ensure that there is some kind of "stop" value that will be reached no matter what, your function may recurse (and you may curse a few times yourself) infinitely.

The Include and Require Statements
Another way to make your code easier to use and maintain is to use include files. Actually, you've used them several times already and have seen how easy it is to bring external files into the current script and run them. All you have to do is use either the include or require constructs (remember, they're language constructs, not functions, even though they are called in a similar fashion) with the name of the file you want to bring in, and that's that. The only difference between the two is how they handle failure to bring in the external file. A failure of include results in a warning; a failure of require results in a fatal error.
There are a few fine points about how they work:
• You include or require a file by inserting the construct within PHP code, but parsing drops out of PHP mode and into HTML mode at that point, so you still have to put the code in the included file inside proper PHP delimiters to make it run.
• You may include or require a file from within a function, but if so, any variables created in the code in the included file have local scope within the function.
• The PHP script within the include file is evaluated (run) when it is included. Any PHP variables that have values are available in the main file, just as though the entire block of code had been directly written inside the file.
Here are a few examples of how to write these constructs in your code (you can include full absolute or relative paths if you like):
include("filename")
require ("filename");
For example, to include the file test.txt, you would type:
include("test.txt");
If the file test. txt contained the text "Hello", then this text would be included on the Web page, just as though it had been coded directly into it.
Interestingly, within the include or require functions you can also add variable names or concatenate them to the name of the filename, inside the brackets, as long as it creates a legal file name:
$Name ="1";
include ("test" . $Name . ".txt");
The result of this concatenation is test1.txt, and if there is a file of that name, it will be included—otherwise an error is generated.
So when are include files handy? Use them to:
• Include text files in the page.
• Define variables and/or constants and details of certain error messages.
• Insert the values of HTTP variables in the page.
• Execute a separate PHP script (even when it may return nothing).
• Place commonly used functions that you need but don't want to define in every page.

Things to be Careful About with Include and Require
Many Web servers are not set up to parse .inc files, so it's better to put includes in .php files. That way their (potentially sensitive) contents are never visible unintentionally to the everyone out there. For example, if someone knows (or just suspects) that you have .inc files on your site (perhaps containing sensitive information such as database passwords), they can simply enter the complete URL in their browser, and they can see the unevaluated source code. Always put a .php extension on your include files to make sure they get evaluated.
And if you want to include another include file via a common.inc.php file that goes at the top of every page (it's a common practice to do this) but worry that some function might accidentally be defined twice, use include_once or require_once. These work the same way as include and require, but will only include the same file once, no matter how many times they are actually included.

Summary
Functions are blocks of code that can be called up within your program. They're either defined automatically in PHP or created by the users themselves (user-defined functions), as demonstrated in this post. They can be thought of as little black boxes that return a value if you feed them the appropriate variables. Variables are passed to them via arguments defined at the beginning of the function. Unless you pass them by reference, the value a function returns doesn't have any effect on the variables outside it. You can use the value the function returns to switch to different cases, and follow different courses of actions.
You saw that variables act differently inside functions because of something called scope. Variables with local scope lasted only while the function was in action, and were then terminated, unless you added the static keyword. Variables defined outside functions had to be used with the global keyword, or the GLOBALS array, inside functions to differentiate them. You also looked at include files and the include(), require(), include_once(), and require_once() functions, and learned how to use them to modularize your code.


Post a Comment

Previous Post Next Post