SlideShare a Scribd company logo
OBJECT ORIENTED PROGRAMMING IN PHP 5
Sayed Ahmed
B.Sc. Engineering in Computer Science & Engineering
M. Sc. in Computer Science
Exploring Computing for 14+ years
sayed@justetc.net
http://sayed.justetc.net
WHAT IS NEW IN PHP 5 FOR OOP
 The Object Model is rewritten
 to allow for
 better performance
 and more features
 PHP 5 treats objects
 as references or handles
 each variable contains an object reference rather than a copy
of the entire object
 See Objects and References
 In PHP 5
 When an object is sent
 by argument, returned or assigned to another variable
 the different variables are not aliases:
 they hold a copy of the identifier (address variable or reference variable)
 which points to the same object
10/9/2011
2
sayed@justetc.net
WHAT IS NEW IN PHP 5 FOR OOP
 PHP 5 has a full object model
 PHP 5 added
 Visibility (private, public, protected)
 abstract classes
 and final classes and methods
 PHP 5 added
 additional
 magic methods
 interfaces
 cloning
 typehinting
10/9/2011
3
sayed@justetc.net
CLASS
 Example
 <?php

class SimpleClass{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}

?>
10/9/2011
4
sayed@justetc.net
CLASS
 Class name can be any valid label which is a not a
PHP reserved word
 A valid class name
 starts with a letter or underscore,
 followed by any number of
 letters, numbers, or underscores
 Regular Expression for class name:
 [a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*
 A class may contain
 constants, variables (called "properties")
 and functions (called "methods")
 The pseudo-variable $this is available
 To call other methods of the same class (within)
10/9/2011
5
sayed@justetc.net
CREATE OBJECTS, CREATE INSTANCES OF CLASSES
 new
 the new keyword must be used to create an instance of
a class
 If the class is in a namespace
 its fully qualified name must be used
 $instance = new SimpleClass();
 A copy of an already created object
 can be made by cloning it
10/9/2011
6
sayed@justetc.net
INHERITANCE : EXTENDS
 The keyword extends is used to
 inherit the methods and properties of another class
 multiple classes inheritance is not allowed
 a class can only inherit from one base class
 The inherited methods and properties can be overridden
by re-declaring them
 Final methods cannot be overridden [final]
 Overridden method signature has to be the same
 Else E_STRICT error will be triggered
 Constructor can be overridden with different parameters
 The overridden methods or static properties can be
accessed by referencing them with parent::.
10/9/2011
7
sayed@justetc.net
PROPERTIES
 Class member variables are called "properties“
 Properties are declared with public, protected, or private
 If declared using var (PHP 4 style), the property will be
defined as public
 However, PHP 5 will generate E_STRICT warning
 public properties can be accessed everywhere
 protected properties can be accessed
 only within the class itself
 and by inherited and parent classes
 private properties may only be accessed by the class
itself
 The default visibility is public
10/9/2011
8
sayed@justetc.net
CLASSES/OBJECT FUNCTIONS
 Table of Contents
 call_user_method_array — Call a user method given with an array of parameters
[deprecated]
 call_user_method — Call a user method on an specific object [deprecated]
 class_alias — Creates an alias for a class
 class_exists — Checks if the class has been defined
 get_called_class — the "Late Static Binding" class name
 get_class_methods — Gets the class methods' names
 get_class_vars — Get the default properties of the class
 get_class — Returns the name of the class of an object
 get_declared_classes — Returns an array with the name of the defined classes
 get_declared_interfaces — Returns an array of all declared interfaces
 get_object_vars — Gets the properties of the given object
 get_parent_class — Retrieves the parent class name for object or class
 interface_exists — Checks if the interface has been defined
 is_a — Checks if the object is of this class or has this class as one of its parents
 is_subclass_of — Checks if the object has this class as one of its parents
 method_exists — Checks if the class method exists
 property_exists — Checks if the object or class has a property
10/9/2011
9
sayed@justetc.net
CLASS CONSTANTS
 Classes can have their own constants
 Interfaces can also have their own constants
 <?php

class MyClass{
const constant = 'constant value';
function showConstant() {
echo self::constant . "n";
}
}
10/9/2011
10
sayed@justetc.net
CLASS CONSTANTS
 Example #2 Static data example
 <?php

class foo {
// As of PHP 5.3.0
const bar = <<<'EOT'
bar
EOT;
}

?>
10/9/2011
11
sayed@justetc.net
AUTOLOADING CLASSES
 You may define an __autoload function which is
automatically called in case you are trying to use a
class/interface which hasn't been defined/included yet
 spl_autoload_register() provides a more flexible
alternative for autoloading classes
 <?php

function __autoload($class_name) {
include $class_name . '.php';
}
$obj = new MyClass1();
$obj2 = new MyClass2();

?>
10/9/2011
12
sayed@justetc.net
SPL_AUTOLOAD_REGISTER EXAMPLE
 <?php
class ClassAutoloader {
public function __construct() {
spl_autoload_register(array($this, 'loader'));
}
private function loader($className) {
echo 'Trying to load ', $className, ' via ',
__METHOD__, "()n";
include $className . '.php';
}
}
$autoloader = new ClassAutoloader();
$obj = new Class1();
$obj = new Class2();
?>
10/9/2011
13
sayed@justetc.net
CONSTRUCTOR
 PHP 5 constructor:
 void __construct ([ mixed $args [, $... ]] )
 Parent constructors are not called implicitly
 if the child class defines a constructor
 parent::__construct() can be used in a child to call
parent constructor
 No E_STRICT error message when __construct()
is overridden with different parameters than the
parent __construct()
 if PHP 5 cannot find a __construct() function for a
given class, it will search for the old-style
constructor function,
10/9/2011
14
sayed@justetc.net
EXAMPLE #2 CONSTRUCTORS IN NAMESPACED CLASSES
 <?php
namespace Foo;
class Bar {
public function Bar() {
// treated as constructor in PHP 5.3.0-5.3.2
// treated as regular method as of PHP 5.3.3
}
}
?>
10/9/2011
15
sayed@justetc.net
DESTRUCTOR
 void __destruct ( void )
 The destructor method will be called
 as soon as there are no other references to a particular object,
 or in any order during the shutdown sequence
 Like constructors
 parent destructors will not be called implicitly by the engine
 In order to run a parent destructor
 one would have to explicitly call parent::__destruct() in the child
destructor body
 The destructor will be called even if script execution is
stopped using exit()
 Exit can be called from destructors to stop execution
 Throwing exceptions from destructors will cause fatal
errors
10/9/2011
16
sayed@justetc.net
SCOPE RESOLUTION OPERATOR (::)
 is a token that allows access to
 static
 constant
 and overridden
 properties or methods of a class
 As of PHP 5.3.0, it's possible to reference the class
using a variable
 $classname = 'MyClass';
 echo $classname::CONST_VALUE; // As of PHP 5.3.0
10/9/2011
17
sayed@justetc.net
STATIC KEYWORD
 Declaring class properties or methods as static
makes them accessible without needing an
instantiation of the class
 A property declared as static can not be accessed
with an instantiated class object (though a static
method can)
 the pseudo-variable $this is not available inside the
method declared as static
 Static properties cannot be accessed through the
object using the arrow operator ->
 Calling non-static methods statically generates an
E_STRICT level warning
10/9/2011
18
sayed@justetc.net
ABSTRACT CLASSES
 Classes defined as abstract may not be instantiated
 and any class that contains at least one abstract
method must also be abstract
 Methods defined as abstract simply declare the
method's signature - they cannot define the
implementation
 When inheriting from an abstract class
 all methods marked abstract in the parent's class
declaration must be defined by the child
 additionally, these methods must be defined with the
same (or a less restricted) visibility
10/9/2011
19
sayed@justetc.net
ABSTRACT CLASSES
 abstract class AbstractClass
{
// Force Extending class to define this method
abstract protected function getValue();
abstract protected function prefixValue($prefix);
// Common method
public function printOut() {
print $this->getValue() . "n";
}
}
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
public function prefixValue($prefix) {
return "{$prefix}ConcreteClass1";
}
}
10/9/2011
20
sayed@justetc.net
OBJECT INTERFACES
 Interfaces are defined
 using the interface keyword
 in the same way as a standard class
 but without any of the methods having their contents defined
 Object interfaces allow
 to create code which specifies which methods a class
must implement
 without having to define how these methods are
handled
 All methods declared in an interface must be public,
this is the nature of an interface
10/9/2011
21
sayed@justetc.net
IMPLEMENTING INTERFACES
 To implement an interface, the implements operator
is used
 Classes may implement more than one interface if
desired by separating each interface with a comma
 A class cannot implement two interfaces that share
function names, since it would cause ambiguity
 Interfaces can be extended like classes using the
extends operator
 The class implementing the interface must use the
exact same method signatures as are defined in the
interface
10/9/2011
22
sayed@justetc.net
INTERFACE CONSTANTS
 interfaces can have constants
 Interface constants works exactly like class
constants
 except they cannot be overridden by a class/interface
that inherits it
10/9/2011
23
sayed@justetc.net
EXAMPLE: INTERFACES
 // Declare the interface 'iTemplate'
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}
 // Implement the interface
// This will work
class Template implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}
return $template;
}
}
10/9/2011
24
sayed@justetc.net
TRAITS
 Traits is a mechanism for code reuse in single inheritance
languages such as PHP
 enabling a developer to reuse sets of methods freely in several
independent classes living in different class hierarchies
 trait ezcReflectionReturnInfo {
function getReturnType() { /*1*/ }
function getReturnDescription() { /*2*/ }
}
class ezcReflectionMethod extends ReflectionMethod {
use ezcReflectionReturnInfo;
/* ... */
}
class ezcReflectionFunction extends ReflectionFunction {
use ezcReflectionReturnInfo;
/* ... */
}
10/9/2011
25
sayed@justetc.net
PRECEDENCE AND TRAITS
 An inherited member from a base class is
overridden by a member inserted by a Trait
 The precedence order is that members from the
current class override Trait methods
 which in return override inherited methods
 Traits override base methods but current methods
override traits
10/9/2011
26
sayed@justetc.net
OVERLOADING
 Overloading in PHP provides
 means to dynamically "create"
 properties and methods
 These dynamic entities are processed
 via magic methods
 one can establish in a class for various action types
 The overloading methods are invoked
 when interacting with properties or methods
 that have not been declared
 or are not visible in the current scope
 All overloading methods must be defined as public
 None of the arguments of these magic methods can be
passed by reference
10/9/2011
27
sayed@justetc.net
METHOD OVERLOADING
 5.3.0 Added __callStatic(). Added warning to
enforce public visibility and non-static declaration
 5.1.0 Added __isset() and __unset()
10/9/2011
28
sayed@justetc.net
PROPERTY OVERLOADING
 void __set ( string $name , mixed $value )
 mixed __get ( string $name )
 bool __isset ( string $name )
 void __unset ( string $name )
 __set() is run when writing data to inaccessible
properties.
 __get() is utilized for reading data from inaccessible
properties.
 __isset() is triggered by calling isset() or empty() on
inaccessible properties.
 __unset() is invoked when unset() is used on
inaccessible properties.
10/9/2011
29
sayed@justetc.net
PROPERTY OVERLOADING
 Property overloading only works in object context
10/9/2011
30
sayed@justetc.net
METHOD OVERLOADING
 Method overloading
 mixed __call ( string $name , array $arguments )
 mixed __callStatic ( string $name , array
$arguments )
 __call() is triggered when invoking inaccessible
methods in an object context
 __callStatic() is triggered when invoking
inaccessible methods in a static context
10/9/2011
31
sayed@justetc.net
ACHIEVING JAVA LIKE OVERLOADING
 If you want to overload a function like in Java, don’t specify any
arguments and use the func_num_args and func_get_args function to
get the number of arguments or the arguments themselves that were
passed to that function:
 function test() {
$args = function_get_args();
swtich (count($args)) {
case 1:
// one argument passed
break;
case 2:
// two arguments passed
break;
default:
// illegal numer of arguments
break;
}
}
 http://stackoverflow.com/questions/1512295/what-is-php-function-
overloading-for
10/9/2011
32
sayed@justetc.net
IS PHP OVERLOADING USEFUL
 When can you use PHP overloading
 Check:
 http://stackoverflow.com/questions/1512295/what-is-php-
function-overloading-for
10/9/2011
33
sayed@justetc.net
OBJECT ITERATION
 PHP 5 provides a way for objects to be defined so it
is possible to iterate through a list of items
 foreach statement. By default, all visible properties
will be used for the iteration.
 you can implement one of PHP 5's internal interface
named Iterator. This allows the object to decide
what and how the object will be iterated.
 Interface methods to override:
 rewind(), current(), key() , next() , valid()
10/9/2011
34
sayed@justetc.net
SPL ITERATORS
 SPL Iterators
 http://ca.php.net/manual/en/spl.iterators.php
 AppendIterator
 ArrayIterator
 CachingIterator
 CallbackFilterIterator
 DirectoryIterator
 EmptyIterator
 FilesystemIterator
 FilterIterator
 GlobIterator
 InfiniteIterator
 IteratorIterator
 LimitIterator
10/9/2011
35
sayed@justetc.net
SPL ITERATORS
 MultipleIterator
 NoRewindIterator
 ParentIterator
 RecursiveArrayIterator
 RecursiveCachingIterator
 RecursiveCallbackFilterIterator
 RecursiveDirectoryIterator
 RecursiveFilterIterator
 RecursiveIteratorIterator
 RecursiveRegexIterator
 RecursiveTreeIterator
 RegexIterator
 SimpleXMLIterator
10/9/2011
36
sayed@justetc.net
PHP PATTERNS
 show a flexible solution to common programming problems.
 Factory
 allows for the instantiation of objects at runtime
 class Example
{
// The parameterized factory method
public static function factory($type)
{
if (include_once 'Drivers/' . $type . '.php') {
$classname = 'Driver_' . $type;
return new $classname;
} else {
throw new Exception('Driver not found');
}
}
}
 // Load a MySQL Driver
$mysql = Example::factory('MySQL');
// Load an SQLite Driver
$sqlite = Example::factory('SQLite');
10/9/2011
37
sayed@justetc.net
PHP PATTERNS
 Singleton
 The Singleton ensures that
 there can be only one instance of a Class
 and provides a global access point to that instance
 often implemented in
 Database Classes
 Loggers
 Front Controllers
 or Request and Response objects
10/9/2011
38
sayed@justetc.net
SINGLETON EXAMPLE
 class Example
{
private static $instance;
private $count = 0;
private function __construct()
{
}
public static function singleton()
{
if (!isset(self::$instance)) {
echo 'Creating new instance.';
$className = __CLASS__;
self::$instance = new $className;
}
return self::$instance;
}
10/9/2011
39
sayed@justetc.net
USE OF SINGLETON
 $singleton = Example::singleton(); // prints "Creatin
g new instance."
echo $singleton->increment(); // 0
echo $singleton->increment(); // 1
$singleton = Example::singleton(); // reuses existing
instance now
echo $singleton->increment(); // 2
echo $singleton->increment(); // 3
// all of these will raise a Fatal Error
$singleton2 = new Example;
$singleton3 = clone $singleton;
$singleton4 = unserialize(serialize($singleton));
10/9/2011
40
sayed@justetc.net
MAGIC METHODS
 __construct(),
 __destruct(),
 __call(),
 __callStatic(),
 __get(),
 __set(),
 __isset(),
 __unset(),
 __sleep(),
 __wakeup(),
 __toString(),
 __invoke(),
 __set_state() and
 __clone()
10/9/2011
41
sayed@justetc.net
MAGIC METHODS
 serialize() checks if your class has a function with
the magic name __sleep().
 unserialize() checks for the presence of a function
with the magic name __wakeup()
10/9/2011
42
sayed@justetc.net
FINAL KEYWORD
 Can be used before
 A class name
 A method name
 Properties cannot be declared final, only classes
and methods may be declared as final.
 prevents child classes from overriding a method by
prefixing the definition with final
 if the class itself is being defined final then it cannot
be extended
10/9/2011
43
sayed@justetc.net
OBJECT CLONING
 To create a copy of an existing object
10/9/2011
44
sayed@justetc.net
COMPARING OBJECTS
 Using ==
 Two object instances are equal if they have the same
attributes and values, and are instances of the same
class.
 Using ===
 object variables are identical if and only if they refer to
the same instance of the same class.
10/9/2011
45
sayed@justetc.net
TYPE HINTING
 Functions are now able to force parameters to be objects or arrays
 // An example class
class MyClass
{
/**
* A test function
*
* First parameter must be an object of type OtherClass
*/
public function test(OtherClass $otherclass) {
echo $otherclass->var;
}
/**
* Another test function
*
* First parameter must be an array
*/
public function test_array(array $input_array) {
print_r($input_array);
}
}
10/9/2011
46
sayed@justetc.net
LATE STATIC BINDINGS
 To address the limitations of self::
 Class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // Here comes Late Static Bindings
(instead of self)
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
10/9/2011
47
sayed@justetc.net
OBJECT SERIALIZATION
 serialize() returns a string containing a byte-stream
representation of any value that can be stored in
PHP
 spl_autoload_register() function
10/9/2011
48
sayed@justetc.net
OTHER OOP FEATURES
 namespaces
 http://ca.php.net/manual/en/language.namespaces.php
 Predefined Interfaces
 http://ca.php.net/manual/en/reserved.interfaces.php
 Predefined Exceptions
 http://ca.php.net/manual/en/reserved.exceptions.php
10/9/2011
49
sayed@justetc.net
OOP CHANGELOG
 http://ca.php.net/manual/en/language.oop5.changelog.php
 5.4.0 Changed: If an abstract class defines a signature for the constructor it will
now be enforced.
 5.3.3 Changed: Methods with the same name as the last element of a
namespaced class name will no longer be treated as constructor. This change
doesn't affect non-namespaced classes.
 5.3.0 Changed: Classes that implement interfaces with methods that have default
values in the prototype are no longer required to match the interface's default
value.
 5.3.0 Changed: It's now possible to reference the class using a variable (e.g., echo
$classname::constant;). The variable's value can not be a keyword (e.g., self,
parent or static).
 5.3.0 Changed: An E_WARNING level error is issued if the magic overloading
methods are declared static. It also enforces the public visibility requirement.
 5.3.0 Changed: Prior to 5.3.0, exceptions thrown in the __autoload function could
not be caught in the catch block, and would result in a fatal error. Exceptions now
thrown in the __autoload function can be caught in the catch block, with one
proviso. If throwing a custom exception, then the custom exception class must be
available. The __autoload function may be used recursively to autoload the custom
exception class.
 5.3.0 Added: The __callStatic method.
10/9/2011
50
sayed@justetc.net
OOP CHANGELOG
 5.3.0 Added: heredoc and nowdoc support for class const and property
definitions. Note: heredoc values must follow the same rules as double-
quoted strings, (e.g., no variables within).
 5.3.0 Added: Late Static Bindings.
 5.3.0 Added: The __invoke method.
 5.2.0 Changed: The __toString method was only called when it was
directly combined with echo() or print(). But now, it is called in any string
context (e.g. in printf() with %s modifier) but not in other types contexts
(e.g. with %d modifier). Since PHP
 5.2.0, converting objects without a __toString method to string emits a
E_RECOVERABLE_ERROR level error.
 5.1.3 Changed: In previous versions of PHP 5, the use of var was
considered deprecated and would issue an E_STRICT level error. It's no
longer deprecated, therefore does not emit the error.
 5.1.0 Changed: The __set_state static method is now called for classes
exported by var_export(). 5.1.0 Added: The __isset and __unset
methods.
10/9/2011
51
sayed@justetc.net
REFERENCES
 http://ca.php.net/manual/en/language.oop5.php
10/9/2011
52
sayed@justetc.net
Ad

Recommended

java-06inheritance
java-06inheritance
Arjun Shanka
 
Interface
Interface
kamal kotecha
 
packages and interfaces
packages and interfaces
madhavi patil
 
Unit 4 Java
Unit 4 Java
arnold 7490
 
Interfaces c#
Interfaces c#
Nipam Medhi
 
Java interface
Java interface
Md. Tanvir Hossain
 
Fundamentals of oops in .Net
Fundamentals of oops in .Net
Harman Bajwa
 
Interfaces in java
Interfaces in java
Abishek Purushothaman
 
Java interfaces
Java interfaces
Raja Sekhar
 
Java interface
Java interface
Arati Gadgil
 
Understanding Interfaces
Understanding Interfaces
Bhushan Mulmule
 
Test Presentation
Test Presentation
Robert Rico Edited
 
C# interview
C# interview
Thomson Reuters
 
INHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
INHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
Venugopalavarma Raja
 
Inheritance chepter 7
Inheritance chepter 7
kamal kotecha
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
object oriented programming language by c++
object oriented programming language by c++
Mohamad Al_hsan
 
Inheritance
Inheritance
Prof. Dr. K. Adisesha
 
Binding,interface,abstarct class
Binding,interface,abstarct class
vishal choudhary
 
Java access modifiers
Java access modifiers
Srinivas Reddy
 
java interface and packages
java interface and packages
VINOTH R
 
Access modifiers in java
Access modifiers in java
Madishetty Prathibha
 
My c++
My c++
snathick
 
Unit 5 Java
Unit 5 Java
arnold 7490
 
7 class objects
7 class objects
Docent Education
 
Java interfaces & abstract classes
Java interfaces & abstract classes
Shreyans Pathak
 
Java Interface
Java Interface
Manish Tiwari
 
Object Oriented Programming in PHP
Object Oriented Programming in PHP
wahidullah mudaser
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
ShaownRoy1
 
OOP in PHP
OOP in PHP
Henry Osborne
 

More Related Content

What's hot (19)

Java interfaces
Java interfaces
Raja Sekhar
 
Java interface
Java interface
Arati Gadgil
 
Understanding Interfaces
Understanding Interfaces
Bhushan Mulmule
 
Test Presentation
Test Presentation
Robert Rico Edited
 
C# interview
C# interview
Thomson Reuters
 
INHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
INHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
Venugopalavarma Raja
 
Inheritance chepter 7
Inheritance chepter 7
kamal kotecha
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
object oriented programming language by c++
object oriented programming language by c++
Mohamad Al_hsan
 
Inheritance
Inheritance
Prof. Dr. K. Adisesha
 
Binding,interface,abstarct class
Binding,interface,abstarct class
vishal choudhary
 
Java access modifiers
Java access modifiers
Srinivas Reddy
 
java interface and packages
java interface and packages
VINOTH R
 
Access modifiers in java
Access modifiers in java
Madishetty Prathibha
 
My c++
My c++
snathick
 
Unit 5 Java
Unit 5 Java
arnold 7490
 
7 class objects
7 class objects
Docent Education
 
Java interfaces & abstract classes
Java interfaces & abstract classes
Shreyans Pathak
 
Java Interface
Java Interface
Manish Tiwari
 

Similar to Object oriented programming in php 5 (20)

Object Oriented Programming in PHP
Object Oriented Programming in PHP
wahidullah mudaser
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
ShaownRoy1
 
OOP in PHP
OOP in PHP
Henry Osborne
 
PHP 5
PHP 5
Rafael Corral
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
Introduction to php oop
Introduction to php oop
baabtra.com - No. 1 supplier of quality freshers
 
Only oop
Only oop
anitarooge
 
Object_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdf
GammingWorld2
 
Oopsinphp
Oopsinphp
NithyaNithyav
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in php
Synapseindiappsdevelopment
 
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
ajayparmeshwarmahaja
 
Object oriented programming in php
Object oriented programming in php
Aashiq Kuchey
 
OOP
OOP
thinkphp
 
UNIT III (8).pptx
UNIT III (8).pptx
DrDhivyaaCRAssistant
 
UNIT III (8).pptx
UNIT III (8).pptx
DrDhivyaaCRAssistant
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
PHP OOP
PHP OOP
Oscar Merida
 
Advanced php
Advanced php
hamfu
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
Toni Kolev
 
PHP 5.3 Overview
PHP 5.3 Overview
jsmith92
 
Object Oriented Programming in PHP
Object Oriented Programming in PHP
wahidullah mudaser
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
ShaownRoy1
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
Object_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdf
GammingWorld2
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in php
Synapseindiappsdevelopment
 
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
ajayparmeshwarmahaja
 
Object oriented programming in php
Object oriented programming in php
Aashiq Kuchey
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Advanced php
Advanced php
hamfu
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
Toni Kolev
 
PHP 5.3 Overview
PHP 5.3 Overview
jsmith92
 
Ad

More from Sayed Ahmed (20)

Workplace, Data Analytics, and Ethics
Workplace, Data Analytics, and Ethics
Sayed Ahmed
 
Python py charm anaconda jupyter installation and basic commands
Python py charm anaconda jupyter installation and basic commands
Sayed Ahmed
 
[not edited] Demo on mobile app development using ionic framework
[not edited] Demo on mobile app development using ionic framework
Sayed Ahmed
 
Sap hana-ide-overview-nodev
Sap hana-ide-overview-nodev
Sayed Ahmed
 
Invest wisely
Invest wisely
Sayed Ahmed
 
Will be an introduction to
Will be an introduction to
Sayed Ahmed
 
Whm and cpanel overview hosting control panel overview
Whm and cpanel overview hosting control panel overview
Sayed Ahmed
 
Web application development using zend framework
Web application development using zend framework
Sayed Ahmed
 
Web design and_html_part_3
Web design and_html_part_3
Sayed Ahmed
 
Web design and_html_part_2
Web design and_html_part_2
Sayed Ahmed
 
Web design and_html
Web design and_html
Sayed Ahmed
 
Visual studio ide shortcuts
Visual studio ide shortcuts
Sayed Ahmed
 
Virtualization
Virtualization
Sayed Ahmed
 
User interfaces
User interfaces
Sayed Ahmed
 
Unreal
Unreal
Sayed Ahmed
 
Unit tests in_symfony
Unit tests in_symfony
Sayed Ahmed
 
Telerik this is sayed
Telerik this is sayed
Sayed Ahmed
 
System analysis and_design
System analysis and_design
Sayed Ahmed
 
Symfony 2
Symfony 2
Sayed Ahmed
 
Story telling and_narrative
Story telling and_narrative
Sayed Ahmed
 
Workplace, Data Analytics, and Ethics
Workplace, Data Analytics, and Ethics
Sayed Ahmed
 
Python py charm anaconda jupyter installation and basic commands
Python py charm anaconda jupyter installation and basic commands
Sayed Ahmed
 
[not edited] Demo on mobile app development using ionic framework
[not edited] Demo on mobile app development using ionic framework
Sayed Ahmed
 
Sap hana-ide-overview-nodev
Sap hana-ide-overview-nodev
Sayed Ahmed
 
Will be an introduction to
Will be an introduction to
Sayed Ahmed
 
Whm and cpanel overview hosting control panel overview
Whm and cpanel overview hosting control panel overview
Sayed Ahmed
 
Web application development using zend framework
Web application development using zend framework
Sayed Ahmed
 
Web design and_html_part_3
Web design and_html_part_3
Sayed Ahmed
 
Web design and_html_part_2
Web design and_html_part_2
Sayed Ahmed
 
Web design and_html
Web design and_html
Sayed Ahmed
 
Visual studio ide shortcuts
Visual studio ide shortcuts
Sayed Ahmed
 
Unit tests in_symfony
Unit tests in_symfony
Sayed Ahmed
 
Telerik this is sayed
Telerik this is sayed
Sayed Ahmed
 
System analysis and_design
System analysis and_design
Sayed Ahmed
 
Story telling and_narrative
Story telling and_narrative
Sayed Ahmed
 
Ad

Recently uploaded (20)

Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Daily Lesson Log MATATAG ICT TEchnology 8
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
All Things Open
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Daily Lesson Log MATATAG ICT TEchnology 8
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
All Things Open
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 

Object oriented programming in php 5

  • 1. OBJECT ORIENTED PROGRAMMING IN PHP 5 Sayed Ahmed B.Sc. Engineering in Computer Science & Engineering M. Sc. in Computer Science Exploring Computing for 14+ years [email protected] http://sayed.justetc.net
  • 2. WHAT IS NEW IN PHP 5 FOR OOP  The Object Model is rewritten  to allow for  better performance  and more features  PHP 5 treats objects  as references or handles  each variable contains an object reference rather than a copy of the entire object  See Objects and References  In PHP 5  When an object is sent  by argument, returned or assigned to another variable  the different variables are not aliases:  they hold a copy of the identifier (address variable or reference variable)  which points to the same object 10/9/2011 2 [email protected]
  • 3. WHAT IS NEW IN PHP 5 FOR OOP  PHP 5 has a full object model  PHP 5 added  Visibility (private, public, protected)  abstract classes  and final classes and methods  PHP 5 added  additional  magic methods  interfaces  cloning  typehinting 10/9/2011 3 [email protected]
  • 4. CLASS  Example  <?php  class SimpleClass{ // property declaration public $var = 'a default value'; // method declaration public function displayVar() { echo $this->var; } }  ?> 10/9/2011 4 [email protected]
  • 5. CLASS  Class name can be any valid label which is a not a PHP reserved word  A valid class name  starts with a letter or underscore,  followed by any number of  letters, numbers, or underscores  Regular Expression for class name:  [a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*  A class may contain  constants, variables (called "properties")  and functions (called "methods")  The pseudo-variable $this is available  To call other methods of the same class (within) 10/9/2011 5 [email protected]
  • 6. CREATE OBJECTS, CREATE INSTANCES OF CLASSES  new  the new keyword must be used to create an instance of a class  If the class is in a namespace  its fully qualified name must be used  $instance = new SimpleClass();  A copy of an already created object  can be made by cloning it 10/9/2011 6 [email protected]
  • 7. INHERITANCE : EXTENDS  The keyword extends is used to  inherit the methods and properties of another class  multiple classes inheritance is not allowed  a class can only inherit from one base class  The inherited methods and properties can be overridden by re-declaring them  Final methods cannot be overridden [final]  Overridden method signature has to be the same  Else E_STRICT error will be triggered  Constructor can be overridden with different parameters  The overridden methods or static properties can be accessed by referencing them with parent::. 10/9/2011 7 [email protected]
  • 8. PROPERTIES  Class member variables are called "properties“  Properties are declared with public, protected, or private  If declared using var (PHP 4 style), the property will be defined as public  However, PHP 5 will generate E_STRICT warning  public properties can be accessed everywhere  protected properties can be accessed  only within the class itself  and by inherited and parent classes  private properties may only be accessed by the class itself  The default visibility is public 10/9/2011 8 [email protected]
  • 9. CLASSES/OBJECT FUNCTIONS  Table of Contents  call_user_method_array — Call a user method given with an array of parameters [deprecated]  call_user_method — Call a user method on an specific object [deprecated]  class_alias — Creates an alias for a class  class_exists — Checks if the class has been defined  get_called_class — the "Late Static Binding" class name  get_class_methods — Gets the class methods' names  get_class_vars — Get the default properties of the class  get_class — Returns the name of the class of an object  get_declared_classes — Returns an array with the name of the defined classes  get_declared_interfaces — Returns an array of all declared interfaces  get_object_vars — Gets the properties of the given object  get_parent_class — Retrieves the parent class name for object or class  interface_exists — Checks if the interface has been defined  is_a — Checks if the object is of this class or has this class as one of its parents  is_subclass_of — Checks if the object has this class as one of its parents  method_exists — Checks if the class method exists  property_exists — Checks if the object or class has a property 10/9/2011 9 [email protected]
  • 10. CLASS CONSTANTS  Classes can have their own constants  Interfaces can also have their own constants  <?php  class MyClass{ const constant = 'constant value'; function showConstant() { echo self::constant . "n"; } } 10/9/2011 10 [email protected]
  • 11. CLASS CONSTANTS  Example #2 Static data example  <?php  class foo { // As of PHP 5.3.0 const bar = <<<'EOT' bar EOT; }  ?> 10/9/2011 11 [email protected]
  • 12. AUTOLOADING CLASSES  You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn't been defined/included yet  spl_autoload_register() provides a more flexible alternative for autoloading classes  <?php  function __autoload($class_name) { include $class_name . '.php'; } $obj = new MyClass1(); $obj2 = new MyClass2();  ?> 10/9/2011 12 [email protected]
  • 13. SPL_AUTOLOAD_REGISTER EXAMPLE  <?php class ClassAutoloader { public function __construct() { spl_autoload_register(array($this, 'loader')); } private function loader($className) { echo 'Trying to load ', $className, ' via ', __METHOD__, "()n"; include $className . '.php'; } } $autoloader = new ClassAutoloader(); $obj = new Class1(); $obj = new Class2(); ?> 10/9/2011 13 [email protected]
  • 14. CONSTRUCTOR  PHP 5 constructor:  void __construct ([ mixed $args [, $... ]] )  Parent constructors are not called implicitly  if the child class defines a constructor  parent::__construct() can be used in a child to call parent constructor  No E_STRICT error message when __construct() is overridden with different parameters than the parent __construct()  if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, 10/9/2011 14 [email protected]
  • 15. EXAMPLE #2 CONSTRUCTORS IN NAMESPACED CLASSES  <?php namespace Foo; class Bar { public function Bar() { // treated as constructor in PHP 5.3.0-5.3.2 // treated as regular method as of PHP 5.3.3 } } ?> 10/9/2011 15 [email protected]
  • 16. DESTRUCTOR  void __destruct ( void )  The destructor method will be called  as soon as there are no other references to a particular object,  or in any order during the shutdown sequence  Like constructors  parent destructors will not be called implicitly by the engine  In order to run a parent destructor  one would have to explicitly call parent::__destruct() in the child destructor body  The destructor will be called even if script execution is stopped using exit()  Exit can be called from destructors to stop execution  Throwing exceptions from destructors will cause fatal errors 10/9/2011 16 [email protected]
  • 17. SCOPE RESOLUTION OPERATOR (::)  is a token that allows access to  static  constant  and overridden  properties or methods of a class  As of PHP 5.3.0, it's possible to reference the class using a variable  $classname = 'MyClass';  echo $classname::CONST_VALUE; // As of PHP 5.3.0 10/9/2011 17 [email protected]
  • 18. STATIC KEYWORD  Declaring class properties or methods as static makes them accessible without needing an instantiation of the class  A property declared as static can not be accessed with an instantiated class object (though a static method can)  the pseudo-variable $this is not available inside the method declared as static  Static properties cannot be accessed through the object using the arrow operator ->  Calling non-static methods statically generates an E_STRICT level warning 10/9/2011 18 [email protected]
  • 19. ABSTRACT CLASSES  Classes defined as abstract may not be instantiated  and any class that contains at least one abstract method must also be abstract  Methods defined as abstract simply declare the method's signature - they cannot define the implementation  When inheriting from an abstract class  all methods marked abstract in the parent's class declaration must be defined by the child  additionally, these methods must be defined with the same (or a less restricted) visibility 10/9/2011 19 [email protected]
  • 20. ABSTRACT CLASSES  abstract class AbstractClass { // Force Extending class to define this method abstract protected function getValue(); abstract protected function prefixValue($prefix); // Common method public function printOut() { print $this->getValue() . "n"; } } class ConcreteClass1 extends AbstractClass { protected function getValue() { return "ConcreteClass1"; } public function prefixValue($prefix) { return "{$prefix}ConcreteClass1"; } } 10/9/2011 20 [email protected]
  • 21. OBJECT INTERFACES  Interfaces are defined  using the interface keyword  in the same way as a standard class  but without any of the methods having their contents defined  Object interfaces allow  to create code which specifies which methods a class must implement  without having to define how these methods are handled  All methods declared in an interface must be public, this is the nature of an interface 10/9/2011 21 [email protected]
  • 22. IMPLEMENTING INTERFACES  To implement an interface, the implements operator is used  Classes may implement more than one interface if desired by separating each interface with a comma  A class cannot implement two interfaces that share function names, since it would cause ambiguity  Interfaces can be extended like classes using the extends operator  The class implementing the interface must use the exact same method signatures as are defined in the interface 10/9/2011 22 [email protected]
  • 23. INTERFACE CONSTANTS  interfaces can have constants  Interface constants works exactly like class constants  except they cannot be overridden by a class/interface that inherits it 10/9/2011 23 [email protected]
  • 24. EXAMPLE: INTERFACES  // Declare the interface 'iTemplate' interface iTemplate { public function setVariable($name, $var); public function getHtml($template); }  // Implement the interface // This will work class Template implements iTemplate { private $vars = array(); public function setVariable($name, $var) { $this->vars[$name] = $var; } public function getHtml($template) { foreach($this->vars as $name => $value) { $template = str_replace('{' . $name . '}', $value, $template); } return $template; } } 10/9/2011 24 [email protected]
  • 25. TRAITS  Traits is a mechanism for code reuse in single inheritance languages such as PHP  enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies  trait ezcReflectionReturnInfo { function getReturnType() { /*1*/ } function getReturnDescription() { /*2*/ } } class ezcReflectionMethod extends ReflectionMethod { use ezcReflectionReturnInfo; /* ... */ } class ezcReflectionFunction extends ReflectionFunction { use ezcReflectionReturnInfo; /* ... */ } 10/9/2011 25 [email protected]
  • 26. PRECEDENCE AND TRAITS  An inherited member from a base class is overridden by a member inserted by a Trait  The precedence order is that members from the current class override Trait methods  which in return override inherited methods  Traits override base methods but current methods override traits 10/9/2011 26 [email protected]
  • 27. OVERLOADING  Overloading in PHP provides  means to dynamically "create"  properties and methods  These dynamic entities are processed  via magic methods  one can establish in a class for various action types  The overloading methods are invoked  when interacting with properties or methods  that have not been declared  or are not visible in the current scope  All overloading methods must be defined as public  None of the arguments of these magic methods can be passed by reference 10/9/2011 27 [email protected]
  • 28. METHOD OVERLOADING  5.3.0 Added __callStatic(). Added warning to enforce public visibility and non-static declaration  5.1.0 Added __isset() and __unset() 10/9/2011 28 [email protected]
  • 29. PROPERTY OVERLOADING  void __set ( string $name , mixed $value )  mixed __get ( string $name )  bool __isset ( string $name )  void __unset ( string $name )  __set() is run when writing data to inaccessible properties.  __get() is utilized for reading data from inaccessible properties.  __isset() is triggered by calling isset() or empty() on inaccessible properties.  __unset() is invoked when unset() is used on inaccessible properties. 10/9/2011 29 [email protected]
  • 30. PROPERTY OVERLOADING  Property overloading only works in object context 10/9/2011 30 [email protected]
  • 31. METHOD OVERLOADING  Method overloading  mixed __call ( string $name , array $arguments )  mixed __callStatic ( string $name , array $arguments )  __call() is triggered when invoking inaccessible methods in an object context  __callStatic() is triggered when invoking inaccessible methods in a static context 10/9/2011 31 [email protected]
  • 32. ACHIEVING JAVA LIKE OVERLOADING  If you want to overload a function like in Java, don’t specify any arguments and use the func_num_args and func_get_args function to get the number of arguments or the arguments themselves that were passed to that function:  function test() { $args = function_get_args(); swtich (count($args)) { case 1: // one argument passed break; case 2: // two arguments passed break; default: // illegal numer of arguments break; } }  http://stackoverflow.com/questions/1512295/what-is-php-function- overloading-for 10/9/2011 32 [email protected]
  • 33. IS PHP OVERLOADING USEFUL  When can you use PHP overloading  Check:  http://stackoverflow.com/questions/1512295/what-is-php- function-overloading-for 10/9/2011 33 [email protected]
  • 34. OBJECT ITERATION  PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items  foreach statement. By default, all visible properties will be used for the iteration.  you can implement one of PHP 5's internal interface named Iterator. This allows the object to decide what and how the object will be iterated.  Interface methods to override:  rewind(), current(), key() , next() , valid() 10/9/2011 34 [email protected]
  • 35. SPL ITERATORS  SPL Iterators  http://ca.php.net/manual/en/spl.iterators.php  AppendIterator  ArrayIterator  CachingIterator  CallbackFilterIterator  DirectoryIterator  EmptyIterator  FilesystemIterator  FilterIterator  GlobIterator  InfiniteIterator  IteratorIterator  LimitIterator 10/9/2011 35 [email protected]
  • 36. SPL ITERATORS  MultipleIterator  NoRewindIterator  ParentIterator  RecursiveArrayIterator  RecursiveCachingIterator  RecursiveCallbackFilterIterator  RecursiveDirectoryIterator  RecursiveFilterIterator  RecursiveIteratorIterator  RecursiveRegexIterator  RecursiveTreeIterator  RegexIterator  SimpleXMLIterator 10/9/2011 36 [email protected]
  • 37. PHP PATTERNS  show a flexible solution to common programming problems.  Factory  allows for the instantiation of objects at runtime  class Example { // The parameterized factory method public static function factory($type) { if (include_once 'Drivers/' . $type . '.php') { $classname = 'Driver_' . $type; return new $classname; } else { throw new Exception('Driver not found'); } } }  // Load a MySQL Driver $mysql = Example::factory('MySQL'); // Load an SQLite Driver $sqlite = Example::factory('SQLite'); 10/9/2011 37 [email protected]
  • 38. PHP PATTERNS  Singleton  The Singleton ensures that  there can be only one instance of a Class  and provides a global access point to that instance  often implemented in  Database Classes  Loggers  Front Controllers  or Request and Response objects 10/9/2011 38 [email protected]
  • 39. SINGLETON EXAMPLE  class Example { private static $instance; private $count = 0; private function __construct() { } public static function singleton() { if (!isset(self::$instance)) { echo 'Creating new instance.'; $className = __CLASS__; self::$instance = new $className; } return self::$instance; } 10/9/2011 39 [email protected]
  • 40. USE OF SINGLETON  $singleton = Example::singleton(); // prints "Creatin g new instance." echo $singleton->increment(); // 0 echo $singleton->increment(); // 1 $singleton = Example::singleton(); // reuses existing instance now echo $singleton->increment(); // 2 echo $singleton->increment(); // 3 // all of these will raise a Fatal Error $singleton2 = new Example; $singleton3 = clone $singleton; $singleton4 = unserialize(serialize($singleton)); 10/9/2011 40 [email protected]
  • 41. MAGIC METHODS  __construct(),  __destruct(),  __call(),  __callStatic(),  __get(),  __set(),  __isset(),  __unset(),  __sleep(),  __wakeup(),  __toString(),  __invoke(),  __set_state() and  __clone() 10/9/2011 41 [email protected]
  • 42. MAGIC METHODS  serialize() checks if your class has a function with the magic name __sleep().  unserialize() checks for the presence of a function with the magic name __wakeup() 10/9/2011 42 [email protected]
  • 43. FINAL KEYWORD  Can be used before  A class name  A method name  Properties cannot be declared final, only classes and methods may be declared as final.  prevents child classes from overriding a method by prefixing the definition with final  if the class itself is being defined final then it cannot be extended 10/9/2011 43 [email protected]
  • 44. OBJECT CLONING  To create a copy of an existing object 10/9/2011 44 [email protected]
  • 45. COMPARING OBJECTS  Using ==  Two object instances are equal if they have the same attributes and values, and are instances of the same class.  Using ===  object variables are identical if and only if they refer to the same instance of the same class. 10/9/2011 45 [email protected]
  • 46. TYPE HINTING  Functions are now able to force parameters to be objects or arrays  // An example class class MyClass { /** * A test function * * First parameter must be an object of type OtherClass */ public function test(OtherClass $otherclass) { echo $otherclass->var; } /** * Another test function * * First parameter must be an array */ public function test_array(array $input_array) { print_r($input_array); } } 10/9/2011 46 [email protected]
  • 47. LATE STATIC BINDINGS  To address the limitations of self::  Class A { public static function who() { echo __CLASS__; } public static function test() { static::who(); // Here comes Late Static Bindings (instead of self) } } class B extends A { public static function who() { echo __CLASS__; } } B::test(); 10/9/2011 47 [email protected]
  • 48. OBJECT SERIALIZATION  serialize() returns a string containing a byte-stream representation of any value that can be stored in PHP  spl_autoload_register() function 10/9/2011 48 [email protected]
  • 49. OTHER OOP FEATURES  namespaces  http://ca.php.net/manual/en/language.namespaces.php  Predefined Interfaces  http://ca.php.net/manual/en/reserved.interfaces.php  Predefined Exceptions  http://ca.php.net/manual/en/reserved.exceptions.php 10/9/2011 49 [email protected]
  • 50. OOP CHANGELOG  http://ca.php.net/manual/en/language.oop5.changelog.php  5.4.0 Changed: If an abstract class defines a signature for the constructor it will now be enforced.  5.3.3 Changed: Methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.  5.3.0 Changed: Classes that implement interfaces with methods that have default values in the prototype are no longer required to match the interface's default value.  5.3.0 Changed: It's now possible to reference the class using a variable (e.g., echo $classname::constant;). The variable's value can not be a keyword (e.g., self, parent or static).  5.3.0 Changed: An E_WARNING level error is issued if the magic overloading methods are declared static. It also enforces the public visibility requirement.  5.3.0 Changed: Prior to 5.3.0, exceptions thrown in the __autoload function could not be caught in the catch block, and would result in a fatal error. Exceptions now thrown in the __autoload function can be caught in the catch block, with one proviso. If throwing a custom exception, then the custom exception class must be available. The __autoload function may be used recursively to autoload the custom exception class.  5.3.0 Added: The __callStatic method. 10/9/2011 50 [email protected]
  • 51. OOP CHANGELOG  5.3.0 Added: heredoc and nowdoc support for class const and property definitions. Note: heredoc values must follow the same rules as double- quoted strings, (e.g., no variables within).  5.3.0 Added: Late Static Bindings.  5.3.0 Added: The __invoke method.  5.2.0 Changed: The __toString method was only called when it was directly combined with echo() or print(). But now, it is called in any string context (e.g. in printf() with %s modifier) but not in other types contexts (e.g. with %d modifier). Since PHP  5.2.0, converting objects without a __toString method to string emits a E_RECOVERABLE_ERROR level error.  5.1.3 Changed: In previous versions of PHP 5, the use of var was considered deprecated and would issue an E_STRICT level error. It's no longer deprecated, therefore does not emit the error.  5.1.0 Changed: The __set_state static method is now called for classes exported by var_export(). 5.1.0 Added: The __isset and __unset methods. 10/9/2011 51 [email protected]