JavaScript Editor Javascript source editor     Web programming 



Team LiB
Previous Section Next Section

Creating an Object

Explaining the concept of an object is a little difficult: It's a sort of theoretical box of thingsvariables, functions, and so forththat 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 like a little box, with inputs and outputs on either side of it. The input mechanisms are called methods, and methods have properties. Throughout this section, we will look at how classes, methods, and properties all work together to produce various outputs.

By the way

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


The section opened with saying that an object has a structure called a class. In each class, you define a set of characteristics. For example, say that 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 they are initialized 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, they can be reused from one application to another. For example, suppose you write a text-formatting class used in one project and decide you can use that class in another project. Because the 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 quite simple, as you simply 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 8.2, you have proof that your object exists, even though there's nothing in itit's just been named.

Listing 8.2. Proof That Your Class Exists
1: <?php
2: class myClass {
3:      //code will go here
4: }
5: $object1 = new myClass();
6: echo "\$object1 is an ".gettype($object1);
7: ?>

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

This is not a particularly useful class because it does absolutely nothing, but it is valid and shows you how the template works. Next, you'll learn about object properties and methods, increasing the use of 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 var keyword:

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

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

Listing 8.3. Showing Object Properties
1:   <?php
2:   class myCar {
3:      var $color = "silver";
4:      var $make = "Mazda";
5:      var $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 will drive a silver Mazda Protege5, you'll want to change the properties of the myCar object. Listing 8.4 shows you how to do just that.

Listing 8.4. Changing Object Properties
1:   <?php
2:   class myCar {
3:      var $color;
4:      var $make;
5:      var $model;
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

By the Way

In this instance, the $color, $make, and $model properties had no initial values when declared. As long as they're declared, you can use them laterinitial values or not.


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

Object Methods

Methods add functionality to your objects. No longer will they be sitting there, just holding on to their properties for dear lifethey'll actually do something! Listing 8.5 shows just that.

Listing 8.5. 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's 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!

So, 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. This is illustrated in Listing 8.6.

Listing 8.6. Accessing Class Properties Within a Method
1:   <?php
2:   class myClass {
3:      var $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 was changed outside the method in which it was contained. Listing 8.7 shows how this is done.

Listing 8.7. Changing the Value of a Property from Within a Method
1: <?php
2: class myClass {
3:    var $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 46, a new function called setName() was created. When it is called in line 12, it changes the value of $name to Julie. Thus, 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 the setName() function.

In other words, an object is capable of modifying its own propertyin 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, on object inheritance.

    Team LiB
    Previous Section Next Section


    JavaScript Editor Javascript source editor     Web programming