Cover by Rasmus Lerdorf, Peter MacIntyre, Kevin Tatroe

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Declaring a Class

To design your program or code library in an object-oriented fashion, you’ll need to define your own classes, using the class keyword. A class definition includes the class name and the properties and methods of the class. Class names are case-insensitive and must conform to the rules for PHP identifiers. The class name stdClass is reserved. Here’s the syntax for a class definition:

class classname [ extends baseclass ] [ implements interfacename ,
    [interfacename, ... ] ]
{
  [ use traitname, [ traitname, ... ]; ]

  [ visibility $property [ = value ]; ... ]

  [ function functionname (args) {
    // code
    }
    ...
  ]
}

Declaring Methods

A method is a function defined inside a class. Although PHP imposes no special restrictions, most methods act only on data within the object in which the method resides. Method names beginning with two underscores (__) may be used in the future by PHP (and are currently used for the object serialization methods __sleep() and __wakeup(), described later in this chapter, among others), so it’s recommended that you do not begin your method names with this sequence.

Within a method, the $this variable contains a reference to the object on which the method was called. For instance, if you call $rasmus->birthday(), inside the birthday() method, $this holds the same value as $rasmus. Methods use the $this variable to access the properties of the current object and to call other methods on that object.

Here’s a simple class definition of the Person class that ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required