Object-Oriented Programming

Members

  • Members are public by default
  • The declaration for a data member has to be preceded by at least one keyword
<?php
class MyClass {
public $str1 = 'This is a member';
const str2 = 'This is a constant';
static $str3 = 'This is a static member';
}

$obj = new MyClass();

echo $obj->str1 . "\n"; # member
echo MyClass::str2 . "\n"; # constant
echo MyClass::$str3 . "\n"; # static member
?>

Methods

  • Methods are public by default
<?php
class MyClass {
function foo1() {
echo "foo1\n";
}
static function foo2() {
echo "foo2\n";
}
}

$obj = new MyClass();

$obj->foo1(); # method
MyClass::foo2(); # static method
?>

Constructors

  • If a constructor is defined for a child class, the parent constructor will only be run if it is explicitly called: parent::__construct()
<?php
class MyClass {
function __construct($str) {
echo "$str\n";
}
}

$obj = new MyClass('hello');
?>

PHP5

Features supported

  • Private, public and protected methods and variables
  • Static methods and variables (class methods and variables) (static keyword)
  • Constant class variables (const keyword) (static keyword is not needed)
  • Interfaces (interface and implements keywords)
  • Abstract classes and methods (abstract keyword)
  • Final classes, methods, and variables (final keyword) (cannot be overridden by a child class)
  • Objects as references (objects are always assigned, passed, and returned by reference)
  • Cloning objects (__clone method)
  • Constructors and destructors (__construct, __destruct) (can optionally still use the name of the class as the name of the constructor)
  • Exceptions (throw, try, catch) (Extending the Exception base class involves creating a constructor and a getMessage method)
  • Type hinting (indicate the expected type of a method parameter) (function process_foo_class(foo_class $foo))
  • __call (optional default method for a class) (can be used to indirectly overload functions) (function __call($name,$arguments))
  • __set (optional default method for accessing undefined variables) (function __set($name,$val))
  • __get (optional default method for setting undefined variables) (function __get($name))

Features not supported

  • Multiple inheritance
  • Exceptions (catch all and finally)

PHP4

  • PHP4 is not an OO language, though it provides some OO features.
  • The OO mechanisms are slow and limited.
  • It's best to avoid using OOP in PHP4, unless speed is not at a factor.

Features not supported

  • Static variables (class variables)
  • Protected and private member variables
  • Object references (have to put the object in a variable, and then use a reference to this variable)

Resources URL: 
notes/php/resources
Sources URL: 
notes/php/sources

See Also