Basic Class
<?php
class BasicClass {
private $var1;
protected $var2;
public $var3;
public function __construct($var) {
$this->var1 = $var;
$this->var2 = $var;
$this->var3 = $var;
}
public function doubleVar3() {
$this->var3 = $this->var3 . ' ' . $this->var3;
}
public function getVar1() {
return $this->var1;
}
}
$inst = new BasicClass('foo');
echo $inst->getVar1() . PHP_EOL;
$inst->doubleVar3();
echo $inst->var3;
Constants
<?php
class BasicClass {
const CLASS_CONSTANT = 12.7;
public function multiply($x) {
return $x * self::CLASS_CONSTANT;
}
}
echo BasicClass::CLASS_CONSTANT . PHP_EOL;
$inst = new BasicClass();
echo $inst->multiply(3) . PHP_EOL;
Static Variables & Static Methods
<?php
class BasicClass {
static $staticVariable;
public function __construct($name) {
self::$staticVariable = $name;
}
public static function staticFunction($ohai) {
echo $ohai . PHP_EOL;
}
}
BasicClass::staticFunction('O Hi');
$inst = new BasicClass('foo');
$inst2 = new BasicClass('bar');
echo $inst::$staticVariable . PHP_EOL;
echo $inst2::$staticVariable . PHP_EOL;
Inheritance (1)
<?php
class Animal {
private $name;
public function __construct($name) {
$this->name = $name;
}
protected function say($what) {
return $what;
}
}
class Dog extends Animal {
public function bark() {
echo $this->say('WOOF!');
}
}
$dog = new Dog('Sparky');
$dog->bark();
Inheritance (2)
<?php
class Animal {
private $name;
public function __construct($name) {
$this->name = $name;
}
final function getName() { // cannot be overridden!
echo $this->name;
}
}
class Dog extends Animal {
public function __construct($name) {
echo 'Yo dawg!' . PHP_EOL;
parent::__construct($name); // call parent function
}
}
$dog = new Dog('Sparky');
echo $dog->getName() . PHP_EOL;
Inheritance (3)
<?php
abstract class Animal {
private $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function doTrick();
}
class Dog extends Animal {
private $tricks = array('jump', 'lay down', 'roll over', 'play dead');
public function doTrick() {
return $this->tricks[rand(0, sizeof($this->tricks) - 1)];
}
}
$dog = new Dog('Sparky');
echo $dog->doTrick();