Chapter4.Breaking It Up: Functions


Chapter 4. Breaking It Up: Functions

We've been making a lot of progress when it comes to handling data in the previous few chapterswe've dealt with simple variables, constants, arrays, and even multidimensional arrays. So how about getting more sophisticated at handling code?

You already know that PHP comes with many built-in functions that are ready to be used. In this chapter, we're going to create our own functions.

As your code gets longer, being able to create your own functions is an essential step because it breaks up that code into manageable sections. As you know, functions are sets of statements that can be called by name, which means that they're ideal for packaging your code into manageable chunks. When your scripts get longer than two dozen statements or so, you should consider breaking up things into functions.

Creating functions also facilitates script developmentif you've got a problem in a script that is 2,000 lines long, imagine how hard it will be to find that error. But if you've broken up your code into functions, each of which is only two dozen lines or so, it'll be much easierand when you know that a given function works as it should, you don't have to worry about it anymore.

Breaking up scripts as they get longer is also a good idea in terms of scope. Scope is the visibility of an item, such as a variable, in your scriptfor example, if you have a 2,000 line script, and you use a variable named $counter at the beginning, but then you forget that you've done so and use another variable with the same name near the end of the script, they're actually the same variable. Thus, you have an unintentional conflict because when you use $counter in one place, it'll set its value everywhere.

Restricting code to functions helps solve this unintentional problemthe variables you use in a function can be restricted to the scope of that function. Thus, you don't have to worry about those variables overlapping other variables with the same name by mistakethey cannot escape the scope of the function.

All this and more is coming up in this chapter as we create our own functions, an essential PHP skill.



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net