


















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
PHP FUNCTION'S AND OBJECTS and, website design
Typology: Lecture notes
1 / 26
This page cannot be seen from the preview
Don't miss anything!



















The basic requirements of any programming language include somewhere to store data, a means of directing program flow, and a few bits and pieces such as expression evaluation, file management, and text output. PHP has all these, plus tools like else and elseif to make life easier. But even with all these in your toolkit, programming can be clumsy and tedious, especially if you have to rewrite portions of very similar code each time you need them.
That’s where functions and objects come in. As you might guess, a function is a set of statements that performs a particular function and—optionally—returns a value. You can pull out a section of code that you have used more than once, place it into a func‐ tion, and call the function by name when you want the code.
Functions have many advantages over contiguous, inline code. For example, they:
Objects take this concept a step further. An object incorporates one or more func‐ tions, and the data they use, into a single structure called a class.
In this chapter, you’ll learn all about using functions, from defining and calling them to passing arguments back and forth. With that knowledge under your belt, you’ll start creating functions and using them in your own objects (where they will be referred to as methods).
95
It is now highly unusual (and definitely not recommended) to use any version of PHP lower than 5.4. Therefore, this chapter assumes that this release is the bare minimum version you will be working with. Generally I would recommend version 5.6, or the new ver‐ sion 7.0 or 7.1 (there is no version 6). You can select any of these from the AMPPS control panel, as described in Chapter 2.
PHP comes with hundreds of ready-made, built-in functions, making it a very rich language. To use a function, call it by name. For example, you can see the date func‐ tion in action here:
echo date("l"); // Displays the day of the week
The parentheses tell PHP that you’re referring to a function. Otherwise, it thinks you’re referring to a constant.
Functions can take any number of arguments, including zero. For example, phpinfo, as shown next, displays lots of information about the current installation of PHP and requires no argument. The result of calling this function can be seen in Figure 5-1.
phpinfo();
Figure 5-1. The output of PHP’s built-in phpinfo function
96 | Chapter 5: PHP Functions and Objects
The opening curly brace starts the statements that will execute when you call the function; a matching curly brace must close it. These statements may include one or more return statements, which force the function to cease execution and return to the calling code. If a value is attached to the return statement, the calling code can retrieve it, as we’ll see next.
Let’s take a look at a simple function to convert a person’s full name to lowercase and then capitalize the first letter of each part of the name.
We’ve already seen an example of PHP’s built-in strtoupper function in Example 5-1. For our current function, we’ll use its counterpart, strtolower:
$lowered = strtolower("aNY # of Letters and Punctuation you WANT"); echo $lowered;
The output of this experiment is as follows:
any # of letters and punctuation you want
We don’t want names all lowercase, though; we want the first letter of each part of the name capitalized. (We’re not going to deal with subtle cases such as Mary-Ann or Jo- En-Lai for this example.) Luckily, PHP also provides a ucfirst function that sets the first character of a string to uppercase:
$ucfixed = ucfirst("any # of letters and punctuation you want"); echo $ucfixed;
The output is as follows:
Any # of letters and punctuation you want
Now we can do our first bit of program design: to get a word with its initial letter capitalized, we call strtolower on the string first, and then ucfirst. The way to do this is to nest a call to strtolower within ucfirst. Let’s see why, because it’s impor‐ tant to understand the order in which code is evaluated.
Say you make a simple call to the print function:
print(5-8);
The expression 5-8 is evaluated first, and the output is –3. (As you saw in the previ‐ ous chapter, PHP converts the result to a string in order to display it.) If the expres‐ sion contains a function, that function is evaluated first as well:
print(abs(5-8));
PHP is doing several things in executing that short statement:
98 | Chapter 5: PHP Functions and Objects
It all works because PHP evaluates each element from the inside out. The same proce‐ dure is in operation when we call the following:
ucfirst(strtolower("aNY # of Letters and Punctuation you WANT"))
PHP passes our string to strtolower and then to ucfirst, producing (as we’ve already seen when we played with the functions separately):
Any # of letters and punctuation you want
Now let’s define a function (shown in Example 5-2) that takes three names and makes each one lowercase, with an initial capital letter.
Example 5-2. Cleaning up a full name
function fix_names($n1, $n2, $n3) { $n1 = ucfirst(strtolower($n1)); $n2 = ucfirst(strtolower($n2)); $n3 = ucfirst(strtolower($n3));return $n1. " ". $n2. " ". $n3; } ?>
You may well find yourself writing this type of code, because users often leave their Caps Lock key on, accidentally insert capital letters in the wrong places, and even for‐ get capitals altogether. The output from this example is shown here:
William Henry Gates
We just saw a function returning a single value. There are also ways of getting multi‐ ple values from a function.
The first method is to return them within an array. As you saw in Chapter 3, an array is like a bunch of variables stuck together in a row. Example 5-3 shows how you can use an array to return function values.
PHP Functions | 99
Figure 5-2. Imagining a reference as a thread attached to a variable
Now the function can follow the thread to find the data to be accessed. This avoids all the overhead of creating a copy of the variable just for the function’s use. What’s more, the function can now modify the variable’s value.
This means you can rewrite Example 5-3 to pass references to all the parameters, and then the function can modify these directly (see Example 5-4).
Example 5-4. Passing values to a function by reference
echo $a1. " ". $a2. " ". $a3. "function fix_names(&$n1, &$n2, &$n3) { $n1 = ucfirst(strtolower($n1)); $n2 = ucfirst(strtolower($n2)); $n3 = ucfirst(strtolower($n3)); } ?>
Rather than passing strings directly to the function, you first assign them to variables and print them out to see their “before” values. Then you call the function as before, but within the function definition you place a & symbol in front of each parameter to be passed by reference.
PHP Functions | 101
Now the variables $n1, $n2, and $n3 are attached to “threads” that lead to the values of $a1, $a2, and $a3. In other words, there is one group of values, but two sets of vari‐ able names are allowed to access them.
Therefore, the function fix_names only has to assign new values to $n1, $n2, and $n to update the values of $a1, $a2, and $a3. The output from this code is:
WILLIAM henry gatES William Henry Gates
As you see, both of the echo statements use only the values of $a1, $a2, and $a3.
The better way to give a function access to an externally created variable is by declar‐ ing it to have global access from within the function. The global keyword followed by the variable name gives every part of your code full access to it (see Example 5-5).
Example 5-5. Returning values in global variables
echo $a1. " ". $a2. " ". $a3. "function fix_names() { global $a1; $a1 = ucfirst(strtolower($a1)); global $a2; $a2 = ucfirst(strtolower($a2)); global $a3; $a3 = ucfirst(strtolower($a3)); } ?>
Now you don’t have to pass parameters to the function, and it doesn’t have to accept them. Once declared, these variables retain global access and are available to the rest of your program, including its functions.
A quick reminder of what you know from Chapter 3:
102 | Chapter 5: PHP Functions and Objects
Example 5-7. Including a PHP file only once
// Your code goes here ?>Then, any further attempts to include the same file (with include or include_once) will be ignored. To determine whether the requested file has already been executed, the absolute file path is matched after all relative paths are resolved and the file is found in your include path.
In general, it’s probably best to stick with include_once and ignore the basic include statement. That way, you will never have the problem of files being included multiple times.
A potential problem with include and include_once is that PHP will only attempt to include the requested file. Program execution continues even if the file is not found.
When it is absolutely essential to include a file, require it. For the same reasons I gave for using include_once, I recommend that you generally stick with require_once whenever you need to require a file (see Example 5-8).
Example 5-8. Requiring a PHP file only once
// Your code goes here ?>PHP is in an ongoing process of development, and there are multiple versions. If you need to check whether a particular function is available to your code, you can use the function_exists function, which checks all predefined and user-created functions.
Example 5-9 checks for array_combine, a function specific to PHP version 5.
104 | Chapter 5: PHP Functions and Objects
Example 5-9. Checking for a function’s existence
Using code such as this, you can take advantage of features in newer versions of PHP and yet still have your code run on earlier versions, as long as you replicate any fea‐ tures that are missing. Your functions may be slower than the built-in ones, but at least your code will be much more portable.
You can also use the phpversion function to determine which version of PHP your code is running on. The returned result will be similar to the following, depending on the version:
5.5.
In much the same way that functions represent a huge increase in programming power over the early days of computing, where sometimes the best program naviga‐ tion available was a very basic GOTO or GOSUB statement, object-oriented programming (OOP) takes the use of functions to a whole new level.
Once you get the hang of condensing reusable bits of code into functions, it’s not that great a leap to consider bundling the functions and their data into objects.
Let’s take a social networking site that has many parts. One handles all user functions —that is, code to enable new users to sign up and existing users to modify their details. In standard PHP, you might create a few functions to handle this and embed some calls to the MySQL database to keep track of all the users.
Imagine how much easier it would be to create an object to represent the current user. To do this, you could create a class, perhaps called User, that would contain all the code required for handling users and all the variables needed for manipulating the data within the class. Then, whenever you need to manipulate a user’s data, you could simply create a new object with the User class.
You could treat this new object as if it were the actual user. For example, you could pass the object a name, password, and email address; ask it whether such a user already exists; and, if not, have it create a new user with those attributes. You could
PHP Objects | 105
you deny outside code direct access to its data. The methods you supply are known as the object’s interface.
This approach makes debugging easy: you have to fix faulty code only within a class. Additionally, when you want to upgrade a program, if you have used proper encapsu‐ lation and maintained the same interface, you can simply develop new replacement classes, debug them fully, and then swap them in for the old ones. If they don’t work, you can swap the old ones back in to immediately fix the problem before further debugging the new classes.
Once you have created a class, you may find that you need another class that is simi‐ lar to it but not quite the same. The quick and easy thing to do is to define a new class using inheritance. When you do this, your new class has all the properties of the one it has inherited from. The original class is now called the superclass, and the new one is the subclass (or derived class).
In our jukebox example, if you invent a new jukebox that can play a video along with the music, you can inherit all the properties and methods from the original jukebox superclass and add some new properties (videos) and new methods (a movie player).
An excellent benefit of this system is that if you improve the speed or any other aspect of the superclass, its subclasses will receive the same benefit.
Before you can use an object, you must define a class with the class keyword. Class definitions contain the class name (which is case-sensitive), its properties, and its methods. Example 5-10 defines the class User with two properties, which are $name and $password (indicated by the public keyword—see “Property and Method Scope” on page 114). It also creates a new instance (called $object) of this class.
Example 5-10. Declaring a class and examining an object
class User { public $name, $password;function save_user() { echo "Save User code goes here"; } } ?>
PHP Objects | 107
Here I have also used an invaluable function called print_r. It asks PHP to display information about a variable in human-readable form. (The _r stands for human- readable.) In the case of the new object $object, it displays the following:
User Object ( [name] => [password] => )
However, a browser compresses all the whitespace, so the output in a browser is slightly harder to read:
User Object ( [name] => [password] => )
In any case, the output says that $object is a user-defined object that has the proper‐ ties name and password.
To create an object with a specified class, use the new keyword, like this: $object = new Class. Here are a couple of ways in which we could do this:
$object = new User; $temp = new User('name', 'password');
On the first line, we simply assign an object to the User class. In the second, we pass parameters to the call.
A class may require or prohibit arguments; it may also allow arguments without explicitly requiring them.
Let’s add a few lines to Example 5-10 and check the results. Example 5-11 extends the previous code by setting object properties and calling a method.
Example 5-11. Creating and interacting with an object
";$object->name = "Joe"; $object->password = "mypass"; print_r($object); echo "
";
$object->save_user();
class User
108 | Chapter 5: PHP Functions and Objects
Once you have created an object, it is passed by reference when you pass it as a parameter. In the matchbox metaphor, this is like keeping several threads attached to an object stored in a matchbox, so that you can follow any attached thread to access it.
In other words, making object assignments does not copy objects in their entirety. You’ll see how this works in Example 5-12, where we define a very simple User class with no methods and only the property name.
Example 5-12. Copying an object?
name = "Alice"; $object2 = $object1; $object2->name = "Amy";echo "object1 name = ". $object1->name. "
"; echo "object2 name = ". $object2->name;
class User { public $name; } ?>
Here, we first create the object $object1 and assign the value Alice to the name prop‐ erty. Then we create $object2, assigning it the value of $object1, and assign the value Amy just to the name property of $object2—or so we might think. But this code outputs the following:
object1 name = Amy object2 name = Amy
What has happened? Both $object1 and $object2 refer to the same object, so chang‐ ing the name property of $object2 to Amy also sets that property for $object1.
To avoid this confusion, you can use the clone operator, which creates a new instance of the class and copies the property values from the original instance to the new instance. Example 5-13 illustrates this usage.
Example 5-13. Cloning an object
name = "Alice";110 | Chapter 5: PHP Functions and Objects
$object2 = clone $object1; $object2->name = "Amy";
echo "object1 name = ". $object1->name. "
"; echo "object2 name = ". $object2->name;
class User { public $name; } ?>
Voilà! The output from this code is what we initially wanted:
object1 name = Alice object2 name = Amy
When creating a new object, you can pass a list of arguments to the class being called. These are passed to a special method within the class, called the constructor, which initializes various properties.
To do this you use the function name __construct (that is, construct preceded by two underscore characters), as in Example 5-14.
Example 5-14. Creating a constructor method
You also have the ability to create destructor methods. This ability is useful when code has made the last reference to an object or when a script reaches the end. Example 5-15 shows how to create a destructor method. The destructor can do clean- up such as releasing a connection to a database or some other resource that you reserved within the class. Because you reserved the resource within the class, you have to release it here, or it will stick around indefinitely. Many system-wide prob‐ lems are caused by programs reserving resources and forgetting to release them.
PHP Objects | 111
It is not necessary to explicitly declare properties within classes, as they can be implicitly defined when first used. To illustrate this, in Example 5-17 the class User has no properties and no methods but is legal code.
Example 5-17. Defining a property implicitly
name = "Alice";echo $object1->name;
class User {} ?>
This code correctly outputs the string Alice without a problem, because PHP implic‐ itly declares the property $object1->name for you. But this kind of programming can lead to bugs that are infuriatingly difficult to discover, because name was declared from outside the class.
To help yourself and anyone else who will maintain your code, I advise that you get into the habit of always declaring your properties explicitly within classes. You’ll be glad you did.
Also, when you declare a property within a class, you may assign a default value to it. The value you use must be a constant and not the result of a function or expression. Example 5-18 shows a few valid and invalid assignments.
Example 5-18. Valid and invalid property declarations
In the same way that you can create a global constant with the define function, you can define constants inside classes. The generally accepted practice is to use upper‐ case letters to make them stand out, as in Example 5-19.
PHP Objects | 113
Example 5-19. Defining constants within a class
class Translate { const ENGLISH = 0; const SPANISH = 1; const FRENCH = 2; const GERMAN = 3; // ...static function lookup() { echo self::SPANISH; } } ?>
You can reference constants directly, using the self keyword and double colon oper‐ ator. Note that this code calls the class directly, using the double colon operator at line 1, without creating an instance of it first. As you would expect, the value printed when you run this code is 1.
Remember that once you define a constant, you can’t change it.
PHP provides three keywords for controlling the scope of properties and methods (members):
public Public members can be referenced anywhere, including by other classes and instances of the object. This is the default when variables are declared with the var or public keywords, or when a variable is implicitly declared the first time it is used. The keywords var and public are interchangeable because, although deprecated, var is retained for compatibility with previous versions of PHP. Methods are assumed to be public by default.
protected These members can be referenced only by the object’s class methods and those of any subclasses.
private These members can be referenced only by methods within the same class—not by subclasses.
114 | Chapter 5: PHP Functions and Objects