PHP Classes and Objects

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

Classes and Objects are used to to make your code more efficient and less repetitive by grouping similar tasks.

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 declaration
  • interface <InterfaceName> [ extends <ParentInterface1> [, <ParentInterface2>, ...] ] { } // Interface declaration
  • use <Trait1> [, <Trait2>, ...]; // Use traits
  • [ public | protected | private ] [ static ] $<varName>; // Attribute declaration
  • const <CONST_NAME>; // Constant declaration
  • [ public | protected | private ] [ static ] function <methodName>([args...]) { } // Method declaration

Remarks

Classes and Interface components

Classes may have properties, constants and methods.

  • Properties hold variables in the scope of the object. They may be initialized on declaration, but only if they contain a primitive value.
  • 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.
  • 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(); // Error!
}

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();
}


Got any PHP Question?