8.0 Introduction


In PHP, there are two types of functions: built-in functions and user -defined functions. The recipes and discussions in most of this book have to do with the former, but the focus of this chapter is on the latter. User-defined functions enable you to encapsulate and categorize your code, as much as arrays enable you to encapsulate and categorize your data. PHP provides more than adequate support for functions via the function declaration. Consider the following:

 function hello_world () {     print "Hello World"; } 

This encapsulates the statement print "Hello World" into the function hello_world() . If you wanted to say "Hello World" at any other point in the script, you could simply call the hello_world() function:

 print "I am about to say hello...\n"; hello_world(); print "\nThere you go, I said hello"; 

As you see in the example, PHP enables you to encapsulate blocks of code and then call them at any time. Another ability that you gain when using functions in PHP is passing arguments to a function. Examine the following:

 function say_something ($something) {     print $something; } 

Putting the variable $something between the parentheses on the first line tells PHP that the variable $something will be set by the user within the scope of the function. Knowing this enables us to rewrite the code in the hello_world() example:

 say_something("I am about to say hello... \n"); say_something("Hello World"); say_something("\nThere you go, I said hello"); 

We just created a wrapper for the print function ( print statement, actually, but who's counting). That means whenever you call say_something($something) , it is the same as calling print $something (note that there must be parentheses around the say_something() function call because it is a function, not a statement). This is just one of the many uses of functions in PHP.

As we said earlier, this chapter is about user-defined functions and the different ways that you can use them to create reusable, slim, PHP code. So, here is the first problem/solution pair, which teaches you about



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

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