Object Oriented Programming in PHP 5
Object Oriented Programming in PHP 5
Programming in PHP 5
Why OOP?
Enhanced Flexibility
Abstraction
Modularization
Encapsulation
Extensibility
Reuse of Code
Cost of OOP
Speed
OOP is slow compared to procedural code
Overhead in Initialization and execution
Memory usage
Verbosity
More Code even for small applications
XML DOM
SOAP
MySQLi
History
PHP 3.x
Basic OOP Structure available
PHP 4.x
Enhanced but still limited OOP
PHP 5.x
Reimplemented, Java-like OOP Support
keyword class
__construct() for constructor
old method still supported
keyword private
only available within the class
keyword protected
available within the class and all
children
keyword public
generally available
identical to var from PHP 4.x
keyword static
Access MyClass::$static
can be combined with public,
private or protected
keyword const
Access via MyClass::constant
comparable to define()
can be combined with public,
private or protected
Extending classes
class MyClass {
public $data;
keyword extends
identical to PHP 4.x
if required, parent constructors
must be called manually
class SomeClass {
final public function foo() {
}
}
keyword final
available on class
prohibits use of extends
available on function
prohibits overriding in children
keyword abstract
use on class
prohibits instantiation, enforce
extends
use on function
enforce overriding in extended
classes
keyword implements
keyword interface
Magic methods
class MyClass {
private $data;
public function __get($var) {
return $this->data[$var];
}
public function __set($var,$val) {
$this->data[$var]=$val;
}
public function __call($fn,$arg) {
echo $fn. called;
}
}
function __autoload($class) {
require_once($class.'.php');
}
method __get()
called on read access to vars
enables indirect access to private
method __set()
called on write access to vars
method __call()
overload method calls
Magic methods
class MyClass {
private $data;
public function __get($var) {
return $this->data[$var];
}
public function __set($var,$val) {
$this->data[$var]=$val;
}
public function __call($fn,$arg) {
echo $fn. called;
}
}
function __autoload($class) {
require_once($class.'.php');
}
method __sleep()
called on serialize()
prepare serialization
close database or open files
method __wakeup()
called on unserialize()
re-open connections
function __autoload()
called on undefined classes
require_once() class code
$obj = MyClass::getInstance();