Chapter 8. Classes and Objects

The earliest versions of PHP didn’t support class definition or object orientation. PHP 4 was the first real attempt at an object interface.1 It wasn’t until PHP 5, though, that developers had the complex object interfaces they know and use today.

Classes are defined using the class keyword followed by a full description of the constants, properties, and methods inherent to the class. Example 8-1 introduces a basic class construct in PHP, complete with a scoped constant value, a property, and callable methods.

Example 8-1. Basic PHP class with properties and methods
class Foo
{
    const SOME_CONSTANT = 42;

    public string $hello = 'hello';

    public function __construct(public string $world = 'world') {}

    public function greet(): void
    {
        echo sprintf('%s %s', $this->hello, $this->world);
    }
}

An object can be instantiated with the new keyword and the name of the class; instantiation looks somewhat like a function call. Any parameters passed into this instantiation are transparently passed into the class constructor (the __construct() method) to define the object’s initial state. Example 8-2 illustrates how the class definition from Example 8-1 could be instantiated either with or without default property values.

Example 8-2. Instantiating a basic PHP class
$first = new Foo; 1
$second = new Foo('universe'); 

$first->greet(); 
$second->greet(); 

echo Foo::SOME_CONSTANT ...

Get PHP Cookbook 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.