Working with Objects - PHP Language Structure - Sams Teach Yourself PHP, MySQL and Apache All in One (2012)

Sams Teach Yourself PHP, MySQL and Apache All in One (2012)

Part II. PHP Language Structure

Chapter 9. Working with Objects


In this chapter, you learn the following:

The basic structure of an object

How to create and manipulate objects and the data they contain


Programmers use objects to store and organize data. Object-oriented programming is a type of programming in which the structure of the program (or application) is designed around these objects and their relationships and interactions. Object-oriented programming structures are found in many programming languages, and are also evident in PHP. In fact, many PHP programmers—especially those coming from a highly object-oriented programming background—choose to develop PHP applications in an object-oriented way.

However, in PHP, it is not required that you write your scripts in an object-oriented manner. Many PHP scripts, and in fact most of the ones in this book, are procedural and functional rather than object-oriented. That is to say, the emphasis is on stepping through the use of variables, data and control structures, and subroutines and functions in the course of creating a program. The reason for this is simply that if you are altogether new to programming it’s important to gain experience in procedural programming and the fundamentals of the language before you tackle a programming paradigm that itself has many books written about it. This chapter gives you a brief glimpse into the world of objects, because it is an important data type and concept to be familiar with as you move on to gather even more skills and experience.


Note

If you are coming to PHP with a background in object-oriented programming, this chapter will help you to understand the object model in PHP.


Creating an Object

Explaining the concept of an object is a little difficult if you’ve never encountered the concept before, because it is inherently abstract: It’s a sort of theoretical box of things—variables, functions, and so forth—that exists in a templated structure called a class. Although it’s easy to visualize a scalar variable, such as $color, with a value of red, or an array called $character with three or four different elements inside it, some people have a difficult time visualizing objects.

For now, try to think of an object as a little box with inputs and outputs on either side of it. The input mechanisms are methods, and methods have properties. Throughout this section, we look at how classes, methods, and properties work together to produce various outputs.


Note

If the concept of classes is completely foreign to you, you can supplement your knowledge by reading the “Classes and Objects” chapter in the PHP Manual. You can find it at http://www.php.net/manual/en/language.oop5.php.


As mentioned previously, an object exists in a structure called a class. In each class, you define a set of characteristics. For example, suppose you have created an automobile class. In the automobile class, you might have color, make, and model characteristics. Each automobile object uses all the characteristics, but each object initializes the characteristics to different values, such as silver, Mazda, and Protege5, or red, Porsche, and Boxter.

The whole purpose of using objects is to create reusable code. Because classes are so tightly structured but self-contained and independent of one another, you can reuse them from one application to another. For example, suppose that you write a text-formatting class for one project and decide you can use that class in another project. Because a class is just a set of characteristics, you can pick up the code and use it in the second project, reaching into it with methods specific to the second application but using the inner workings of the existing code to achieve new results.

Creating an object is simple; you just declare it to be in existence:

class myClass {
//code will go here
}

Now that you have a class, you can create a new instance of an object:

$object1 = new myClass();

In Listing 9.1, you have proof that your object exists, even though there’s nothing in it—it’s just been named.

Listing 9.1 Proof That Your Object Exists


1: <?php
2: class myClass {
3: //code will go here
4: }
5: $object1 = new myClass();
6: echo "\$object1 is an ".gettype($object1).".<br/>";
7:
8: if (is_object($object1)) {
9: echo "Really! I swear \$object1 is an object!";
10: }
11: ?>


If you save this code as proofofclass.php, place it in your document root, and access it with your web browser, you will see the following on your screen:

$object1 is an object.
Really! I swear $object1 is an object!

This is not a particularly useful class because it does absolutely nothing, but it is valid and shows you how the class template works in lines 2–5. Lines 8–10 use the is_object() function to test whether something is an object; in this case, the something is $object1. Because the test ofis_object() evaluates to true, the string within the if statement is printed to the screen.

Next, you learn about using object properties and methods within the class template.

Properties of Objects

The variables declared inside an object are called properties. It is standard practice to declare your variables at the top of the class. These properties can be values, arrays, or even other objects. The following snippet uses simple scalar variables inside the class, prefaced with the publickeyword:

class myCar {
public$color = "silver";
public$make = "Mazda";
public$model = "Protege5";
}


Note

If you use the keyword public, protected, or private before the variable name, you can indicate if the class member (the variable) can be accessed everywhere (public), within the class itself or a parent class or an inherited class (protected), or only by the class itself (private).


Now when you create a myCar object, it will always have those three properties. Listing 9.2 shows you how to access properties after they have been declared and values have been assigned to them.

Listing 9.2 Showing Object Properties


1: <?php
2: class myCar {
3: public$color = "silver";
4: public$make = "Mazda";
5: public$model = "Protege5";
6: }
7: $car = new myCar();
8: echo "I drive a: ".$car -> color." ".$car -> make." ".$car -> model;
9: ?>


If you save this code as objproperties.php, place it in your document root, and access it with your web browser, you will see the following on your screen:

I drive a: silver Mazda Protege5

Because the odds are low that you also drive a silver Mazda Protege5, you’ll want to change the properties of the myCar object. Listing 9.3 shows you how to do just that.

Listing 9.3 Changing Object Properties


1: <?php
2: class myCar {
3: public$color = "silver";
4: public$make = "Mazda";
5: public$model = "Protege5";
6: }
7: $car = new myCar();
8: $car -> color = "red";
9: $car -> make = "Porsche";
10: $car -> model = "Boxter";
11: echo "I drive a: ".$car -> color." ".$car -> make." ".$car -> model;
12: ?>


If you save this code as objproperties2.php, place it in your document root, and access it with your web browser, you will see the following on your screen:

I drive a: red Porsche Boxter


Note

In this instance, even if the $color, $make, and $model properties had no initial values when declared, lines 8–10 would assign a value to them. As long as the properties are declared, you can use them later (initial values or not).


The purpose of Listing 9.3 is to show that as long as you have a well-defined class with properties, you can still easily change the values of the properties to fit your needs.

Object Methods

Methods add functionality to your objects. No longer will your objects just sit there, holding on to their properties for dear life—they’ll actually do something! Listing 9.4 shows just that.

Listing 9.4 A Class with a Method


1: <?php
2: class myClass {
3: function sayHello() {
4: echo "HELLO!";
5: }
6: }
7: $object1 = new myClass();
8: $object1 -> sayHello();
9: ?>


Although it is not the most thrilling example of action, if you save this code as helloclass.php, place it in your document root, and access it with your web browser, you will see the following on your screen:

HELLO!

A method looks and acts like a normal function but is defined within the framework of a class. The -> operator is used to call the object method in the context of your script. Had there been any variables stored in the object, the method would have been capable of accessing them for its own purposes, as illustrated in Listing 9.5.

Listing 9.5 Accessing Class Properties Within a Method


1: <?php
2: class myClass {
3: public$name = "Jimbo";
4: function sayHello() {
5: echo "HELLO! My name is ".$this->name;
6: }
7: }
8: $object1 = new myClass();
9: $object1 -> sayHello();
10: ?>


If you save this code as helloclass2.php, place it in your document root, and access it with your web browser, you will see the following on your screen:

HELLO! My name is Jimbo

The special variable $this is used to refer to the currently instantiated object as you see on line 5. Anytime an object refers to itself, you must use the $this variable. Using the $this variable in conjunction with the -> operator enables you to access any property or method in a class, within the class itself.

One final tidbit regarding the basics of working with an object’s properties is how to change a property from within a method. Previously, a property’s value changed outside the method in which it was contained. Listing 9.6 shows how to make the change from inside a method.

Listing 9.6 Changing the Value of a Property from Within a Method


1: <?php
2: class myClass {
3: public$name = "Jimbo";
4: function setName($n) {
5: $this->name = $n;
6: }
7: function sayHello() {
8: echo "HELLO! My name is ".$this->name;
9: }
10: }
11: $object1 = new myClass();
12: $object1 -> setName("Julie");
13: $object1 -> sayHello();
14: ?>


If you save this code as helloclass3.php, place it in your document root, and access it with your web browser, you will see the following on your screen:

HELLO! My name is Julie

Why? Because in lines 4–6 a new function called setName() was created. When it is called in line 12, it changes the value of $name to Julie. Therefore, when the sayHello() function is called in line 13 and it looks for $this->name, it uses Julie, which is the new value that was just set by thesetName() function. In other words, an object can modify its own property—in this case, the $name variable.

Constructors

A constructor is a function that lives within a class and, given the same name as the class, is automatically called when a new instance of the class is created using new classname. Using constructors enables you to provide arguments to your class, which will then be processed immediately when the class is called. You see constructors in action in the next section.

Object Inheritance

Having learned the absolute basics of objects, properties, and methods, you can start to look at object inheritance. Inheritance with regard to classes is just what it sounds like: One class inherits functionality from its parent class. Listing 9.7 shows an example.

Listing 9.7 A Class Inheriting from Its Parent


1: <?php
2: class myClass {
3: public$name = "Matt";
4: function myClass($n) {
5: $this->name = $n;
6: }
7: function sayHello() {
8: echo "HELLO! My name is ".$this->name;
9: }
10: }
11: class childClass extends myClass {
12: //code goes here
13: }
14: $object1 = new childClass("Baby Matt");
15: $object1 -> sayHello();
16: ?>


If you save this code as inheritance.php, place it in your document root, and access it with your web browser, you will see the following on your screen:

HELLO! My name is Baby Matt

Lines 4–6 make up a constructor. Notice that the name of this function is the same as the class in which it is contained: myClass. Lines 11–13 define a second class, childClass, that contains no code. That’s fine because, in this example, the class exists only to demonstrate inheritance from the parent class. The inheritance occurs through the extends clause shown in line 11. The second class inherits the elements of the first class because this clause is used.

Listing 9.8 shows you one last example of how a child class can override the methods of the parent class.

Listing 9.8 The Method of a Child Class Overriding That of Its Parent


1: <?php
2: class myClass {
3: public$name = "Matt";
4: function myClass($n) {
5: $this->name = $n;
6: }
7: function sayHello() {
8: echo "HELLO! My name is ".$this->name;
9: }
10: }
11: class childClass extends myClass {
12: function sayHello() {
13: echo "I will not tell you my name.";
14: }
15: }
16: $object1 = new childClass("Baby Matt");
17: $object1 -> sayHello();
18: ?>


The only changes in this code from Listing 9.7 are the new lines 12–14. In these lines, a function is created called sayHello() that, instead of printing HELLO! My name is..., prints the message I will not tell you my name. Because the sayHello() function now exists in childClass, andchildClass is the class called in line 16, its version of sayHello() is the one used.

If you save this code as inheritance2.php, place it in your document root, and access it with your web browser, you will see the following on your screen:

I will not tell you my name

Like most elements of object-oriented programming, inheritance is useful when attempting to make your code flexible. Suppose that you create a text-formatting class that organizes and stores data, format it in HTML, and output the result to a browser—your own personal masterpiece. Now suppose that you have a client who wants to use that concept, but instead of formatting the content into HTML and sending it to a browser, he wants to format it for plaintext and save it to a text file. No problem; you just add a few methods and properties, and away you go. Finally, the client comes back and says that he really wants the data to be formatted and sent as an email—and then, what the heck, why not create XML-formatted files, as well?

Although you might want to pull your hair out in frustration, you’re really not in a bad situation. If you separate the compilation and storage classes from the formatting classes—one for each of the various delivery methods (HTML, text, email, XML)—you essentially have a parent-child relationship. Consider the parent class as the one that holds the compilation and storage methods. The formatting classes are the children: They inherit the information from the parent and output the result based on their own functionality. Everybody wins.

Summary

This chapter provided a foundation for working with object-oriented code. In no way does this content cover all the aspects of object-oriented programming. Universities teach entire series of classes (no pun intended) devoted to this topic, so you can imagine that these pages are a little light. However, you did learn to create classes and instantiate objects from them. You learned how to create and access the properties and methods of a class, how to build new classes, and how to inherit features from parent classes. That’s not too shabby!

Q&A

Q. Why have I seen var instead of public, private, or protected in property declarations?

A. In earlier versions of PHP, var was used to declare properties in classes. For backward compatibility, if you use code that still says var in it, it will be treated as public and not cause an error (unless you want it to be a private or protected property).

Q. Do I have to understand object-oriented programming to become a good PHP programmer or even to finish this book?

A. Not at all. In fact, the projects in this book are procedural or functional in nature and do not contain object-oriented programming. Object-oriented programming is an organizational approach intended to improve the reusability and extensibility of the code that makes up a given application. You might not know enough about your project in the beginning stages of development to fully plan for an object-oriented design. When it is complete—or, at least, approaching a solid state—you might start to see areas in which an object-oriented approach can be taken, and you might start to combine your code into classes, properties, and methods. But for the most part, you won’t write simple scripts performing particular duties in object-oriented fashion unless it is your background and comes naturally to you. For a great deal more information on the object model in PHP, see the appropriate section of the PHP Manual, at http://www.php.net/manual/en/language.oop5.php.

Workshop

The workshop is designed to help you review what you’ve learned and begin putting your knowledge into practice.

Quiz

1. How can you declare a class called emptyClass that has no methods or properties?

2. How do you choose a name for a constructor method?

3. If a variable is declared private, where can it be used?

Answers

1. Use the class keyword:

class emptyClass {
}

2. You don’t—a constructor is named for the class in which it resides.

3. Variables declared private can only be used in the class itself.

Activities

1. Create a class called baseCalc() that stores two numbers as properties. Next, create a calculate() method that prints the numbers to the browser.

2. Now create classes called addCalc(), subCalc(), mulCalc(), and divCalc() that inherit functionality from baseCalc() but override the calculate() method and print appropriate totals to the browser.