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
classFoo{constSOME_CONSTANT=42;publicstring$hello='hello';publicfunction__construct(publicstring$world='world'){}publicfunctiongreet():void{echosprintf('%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.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access