Classes and Objects
suggest changeVersions
The notes below were written for PHP 4.0 through 7.1. Later versions relax some of the initializer rules.
Introduction
Classes and objects group similar data and behavior so the same structure is not repeated.
A class is used to define the actions and data structure used to build objects. The objects are then built using this predefined structure.
Syntax
class <ClassName> [ extends <ParentClassName> ] [ implements <Interface1> [, <Interface2>, ... ] ] { }// Class declarationinterface <InterfaceName> [ extends <ParentInterface1> [, <ParentInterface2>, ...] ] { }// Interface declarationuse <Trait1> [, <Trait2>, ...]; // Use traits[ public | protected | private ] [ static ] $<varName>;// Attribute declarationconst <CONST_NAME> = <value>;// Constant declaration. A value is required.[ public | protected | private ] [ static ] function <methodName>([args...]) { }// Method declaration
Remarks
Classes and Interface components
Classes may have properties, constants and methods.
- Properties hold values on the object. Through PHP 8.0, a default value must be a constant expression (
newin a property default is a syntax error until PHP 8.1). - Constants must be given a value on declaration. Before PHP 5.6 that value had to be a scalar. They cannot be assigned at run time.
- Methods must have a body, even an empty one, unless the method is declared abstract.
class Foo {
private $foo = 'foo'; // OK
private $baz = array(); // OK
private $bar = new Bar(); // Syntax error before PHP 8.1
}
Interfaces cannot have properties, but may have constants and methods.
- Interface constants must be initialized on declaration and can only contain a primitive value. Constant values are fixed at compile time and may not be assigned at run time.
- Interface methods have no body.
interface FooBar {
const FOO_VALUE = 'bla';
public function doAnything();
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents