In PHP, to define a class that inherits from another, we use the keyword extends
:
class ChildClass extends ParentClass {}
The newly defined class can access members with public
and protected
visibility from the base class, but cannot access private
members.
The newly defined class can also redefine or override class members.
// Dog class inherits from Pet class.class Dog extends Pet {function bark() {return "woof";}}
A constructor method is one of several magic methods provided by PHP. This method is automatically called when an object is instantiated. A constructor method is defined with the special method name __construct
. The constructor can be used to initialize an object’s properties.
// constructor with no arguments:class Person {public $favorite_color;function __construct() {$this->favorite_color = "blue";}}// constructor with arguments:class Person {public $favorite_color;function __construct($color) {$this->favorite_color = $color;}}
In PHP, classes are defined using the class
keyword.
Functions defined within a class become methods and variables within the class are considered properties.
There are three levels of visibility for class members:
public
(default) - accessible from outside of the classprotected
- only accessible within the class or its descendantsprivate
- only accessible within the defining classMembers can be defined to be static:
::
)Classes are instantiated into objects using the new
keyword. Members of an object are accessed using the Object Operator (->
).
// Test classclass Test {public $color = "blue";protected $shape = "sphere";private $quantity = 10;public static $number = 42;public static function returnHello() {return "Hello";}}// instantiate new object$object = new Test();// only color can be accessed from the instanceecho $object->color; # Worksecho $object->shape; # Failsecho $object->quantity; # Failsecho $object->number; # Fails// we use the static class to access numberecho Test::$number;