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, ...

Get Sams Teach Yourself PHP in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.