4.3. Defining a Class

After you've determined the objects, properties, and methods your project requires, you're ready to define classes. The class is the template (pattern) for the object.

4.3.1. Writing a class statement

You write the class statement to define the properties and methods for the class. The class statement has the following general format:

class className
{

    Add statements that define the properties
    Add all the methods
}

You can use any valid PHP identifier for the class name, except the name stdClass. PHP uses the name stdClass internally, so you can't use this name.

All the property settings and method definitions are enclosed in the opening and closing curly braces. If you want a class to be a subclass that inherits properties and methods, use a statement similar to the following:

class whiteRose extends Rose
{
    Add the property statements
    Add the methods
}

The object created from this class has access to all the properties and methods of both the whiteRose child class and the Rose class. The Rose class, however, doesn't have access to properties or methods in the child class, whiteRose. Imagine, the child owns everything the parent owns, but the parent owns nothing of the child's. What an idea.

The next few sections show you how to set properties and define methods within the class statement. For a more comprehensive example of a complete class statement, see the section, "Putting it all together," later in this chapter.

4.3.2. Setting properties

When you're ...

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® 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.