Basic Classes

To define a class, use the class keyword followed by the class name:

class Person {

}

This code creates a Person class. This is not a very exciting class, because it lacks methods or properties. Class names in PHP are case-insensitive, so you cannot define both a Person and a PERSON class.

Use this class name to instantiate a new instance of your object:

$rasmus = new Person;

Alternatively, to determine a class from an object instance, use get_class( ):

$person = new Person;
print get_class($person)
Person

Even though class names are case-insensitive, PHP 5 preserves their capitalization. This is different from PHP 4, where PHP converts the name to lowercase. In PHP 4, calling get_class( ) on an instance of the Person class produced person. PHP 5 returns the correct class name.

Properties

List class properties at the top of the class:

class Person {
    public $name;
}

This creates a public property named name. When a property is public, it can be read from and written to anywhere in the program:

$rasmus = new Person;
$rasmus->name = 'Rasmus Lerdorf';

Properties in PHP 4 are declared using a different syntax: var. This syntax is deprecated in favor of public, but for backward compatibility, var is still legal. The behavior of a property declared using public and var is identical.

Never use public properties. Doing so makes it easy to violate encapsulation. Always use accessor methods instead.

You don’t need to predeclare a property inside the class to use it. For instance: ...

Get Upgrading to PHP 5 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.