Skip to content

Instantly share code, notes, and snippets.

@sherbrow
Last active January 23, 2016 15:31
Show Gist options
  • Save sherbrow/af69ce734d7f2e5f66b4 to your computer and use it in GitHub Desktop.
Save sherbrow/af69ce734d7f2e5f66b4 to your computer and use it in GitHub Desktop.
Ultimate PHP v5 class declaration aka the simplest most complex class definition in PHP
<?php
/* Ultimate PHP v5 class declaration */
/** TODO
* - interfaces http://php.net/manual/language.oop5.interfaces.php
* - abstract http://php.net/manual/language.oop5.abstract.php
* - traits http://php.net/manual/language.oop5.traits.php
* - magic methods http://php.net/manual/language.oop5.magic.php
*/
class MyClass
{
public $publicProp;
protected $protectedProp;
private $privateProp;
var $someProperty;
const CONSTANT = 'value';
static $classProp;
public function __construct($param) {
$this; // this instance
$this->someProperty;
// self == this class
self::CONSTANT;
self::$classProp;
}
public function __destruct() {}
public function publicMethod() {}
protected function protectedMethod() {}
private function privateMethod() {}
function someMethod($param1, $paramOpt = '') {
$this->someProperty = $param1;
return 1;
}
function scopeMethod() {
__CLASS__; // 'MyClass'
// static == calling scope class (depends on called class, i.e. farthest leaf of inheritance tree overriding CONSTANT)
static::CONSTANT; // value (if called "on" MyClass)
static::CONSTANT; // subvalue (if called "on" MySubClass)
static::CONSTANT; // ubersubvalue (if called "on" MyUberSubClass)
}
final function finalMethod() {}
static function classMethod() {}
final public static function unshakableClassMethod() {}
}
$myObject = new MyClass('param');
$myObject->publicProp;
$myObject->publicMethod();
MyClass::CONSTANT;
MyClass::$classProp;
MyClass::classMethod();
class MySubClass extends MyClass
{
const CONSTANT = 'subvalue';
public function __construct() {
parent::__construct(null);
$this->protectedProp;
$this->protectedMethod();
// all calls forward calling scope
parent::scopeMethod(); MyClass::scopeMethod();
self::scopeMethod(); MySubClass::scopeMethod();
static::scopeMethod(); // MySubClass::scopeMethod() (if called "on" MySubClass)
static::scopeMethod(); // MyUberSubClass::scopeMethod() (if called "on" MyUberSubClass)
}
function scopeMethod() {
__CLASS__; // 'MySubClass'
parent::scopeMethod(); MyClass::scopeMethod(); // calls forward calling scope
parent::CONSTANT; MyClass::CONSTANT; // value
self::CONSTANT; MySubClass::CONSTANT; // subvalue
static::CONSTANT; // subvalue (if called "on" MySubClass)
static::CONSTANT; // ubersubvalue (if called "on" MyUberSubClass)
}
}
class MyUberSubClass extends MySubClass
{
const CONSTANT = 'ubersubvalue';
}
$myObject->scopeMethod();
$mySubObject = new MySubClass();
$mySubObject->scopeMethod();
$myUberSubObject = new MyUberSubClass();
$myUberSubObject->scopeMethod();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment