[ Team LiB ] Previous Section Next Section

Creating an Object

To create an object, you must first design the template from which it can be instantiated. This template is known as a class, and in PHP, you must declare it with the class keyword:

class Item {
  // a very minimal class

The Item class is the basis from which you can instantiate any number of Item objects. To create an instance of an object, you must use the new statement:

$obj1 = new Item();
$obj2 = new Item();
print "\$obj1 is an ".gettype($obj1)."<br />";
print "\$obj2 is an ".gettype($obj2)."<br />";

You can test that $obj1 and $obj2 contain objects with PHP's gettype() function. gettype() accepts any variable and returns a string that should tell you what you are dealing with. In a loosely typed language like PHP, gettype() is useful when checking arguments sent to functions. In the previous code fragment, gettype() returns the string "object", which is then written to the browser.

So you have confirmed that you have created two objects. Of course, they're not very useful yet, but they help to make an important point. You can think of a class as a mold with which you can press as many objects as you want. Let's add some more features to the class to make your objects a little more interesting.

    [ Team LiB ] Previous Section Next Section