Classes in PHP5
Illustrates how to create and use a basic class in PHP5.
Basic:
<?php Class MyCar { public $name; function __construct($name) { $this->name = $name; } function __destruct() { echo '*crash* this car has been destroyed'; } function drive() { echo 'Vrooooom... ' . $this->name; } } // Instance 1 $porsche = new MyCar('Porsche'); $porsche->drive(); echo ''; unset($porsche); ?>
Inheritance:
<?php Class MyCar { public $name; function __construct($name) { $this->name = $name; } function drive() { echo 'Vroooom... ' . $this->name; } } Class PorscheCar Extends MyCar { function drive() { echo 'VROOOOOOOOM... ' . $this->name; echo ''; // Call original method from parent class parent::drive(); } } $boxster = new PorscheCar('Boxster 987'); $boxster->drive(); ?>
Visibility note:
There are three scope definitions. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited classes. Members declared as private may only be accessed by the class that defines the member. Class properties must be defined as public, private, or protected. If declared using var, the property will be defined as public. Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.
Learn more here.