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

More Related Content

PPT
Oops concepts in php
PPTX
Object oreinted php | OOPs
PPT
Oops in PHP
PPTX
OOPS Characteristics (With Examples in PHP)
PPT
Oops in PHP By Nyros Developer
PPT
Introduction to OOP with PHP
PPT
Php Oop
Oops concepts in php
Object oreinted php | OOPs
Oops in PHP
OOPS Characteristics (With Examples in PHP)
Oops in PHP By Nyros Developer
Introduction to OOP with PHP
Php Oop

What's hot (20)

PPTX
Php oop presentation
PDF
OOP in PHP
PPT
PHP - Introduction to Object Oriented Programming with PHP
PPTX
Introduction to PHP OOP
PPT
PHP- Introduction to Object Oriented PHP
PPT
Class 7 - PHP Object Oriented Programming
PDF
09 Object Oriented Programming in PHP #burningkeyboards
ODP
Beginners Guide to Object Orientation in PHP
PPTX
Oop in-php
PPTX
Intro to OOP PHP and Github
PDF
Object Oriented Programming in PHP
PDF
A Gentle Introduction To Object Oriented Php
PPTX
Oops in php
PDF
Object Oriented Programming with PHP 5 - More OOP
PPT
Class and Objects in PHP
PPTX
Only oop
ZIP
Object Oriented PHP5
PPTX
Chapter 07 inheritance
PDF
Intermediate OOP in PHP
Php oop presentation
OOP in PHP
PHP - Introduction to Object Oriented Programming with PHP
Introduction to PHP OOP
PHP- Introduction to Object Oriented PHP
Class 7 - PHP Object Oriented Programming
09 Object Oriented Programming in PHP #burningkeyboards
Beginners Guide to Object Orientation in PHP
Oop in-php
Intro to OOP PHP and Github
Object Oriented Programming in PHP
A Gentle Introduction To Object Oriented Php
Oops in php
Object Oriented Programming with PHP 5 - More OOP
Class and Objects in PHP
Only oop
Object Oriented PHP5
Chapter 07 inheritance
Intermediate OOP in PHP
Ad

Similar to Object oriented programming in php 5 (20)

PDF
Object Oriented Programming in PHP
PPTX
Lecture-10_PHP-OOP.pptx
PPTX
OOP in PHP
PDF
PDF
Object_oriented_programming_OOP_with_PHP.pdf
PPTX
Oopsinphp
PPT
Synapseindia object oriented programming in php
PPTX
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
PPTX
Object oriented programming in php
PPT
PPTX
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
PPTX
UNIT III (8).pptx
PPTX
UNIT III (8).pptx
PDF
PHP OOP
PPT
Advanced php
PPTX
FFW Gabrovo PMG - PHP OOP Part 3
PDF
PHP 5.3 Overview
PDF
OOP in PHP
PPTX
Chap4 oop class (php) part 2
PPT
UNIT-IV WT web technology for 1st year cs
Object Oriented Programming in PHP
Lecture-10_PHP-OOP.pptx
OOP in PHP
Object_oriented_programming_OOP_with_PHP.pdf
Oopsinphp
Synapseindia object oriented programming in php
c91632a4-2e92-4edf-b750-358da15ed1b1.pptx
Object oriented programming in php
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
UNIT III (8).pptx
UNIT III (8).pptx
PHP OOP
Advanced php
FFW Gabrovo PMG - PHP OOP Part 3
PHP 5.3 Overview
OOP in PHP
Chap4 oop class (php) part 2
UNIT-IV WT web technology for 1st year cs
Ad

More from Sayed Ahmed (20)

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

Recently uploaded (20)

PPTX
Cloud computing and distributed systems.
PPTX
A Presentation on Artificial Intelligence
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
Big Data Technologies - Introduction.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
cuic standard and advanced reporting.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
Cloud computing and distributed systems.
A Presentation on Artificial Intelligence
Understanding_Digital_Forensics_Presentation.pptx
NewMind AI Weekly Chronicles - August'25 Week I
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
NewMind AI Monthly Chronicles - July 2025
Big Data Technologies - Introduction.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Building Integrated photovoltaic BIPV_UPV.pdf
Network Security Unit 5.pdf for BCA BBA.
Encapsulation_ Review paper, used for researhc scholars
Per capita expenditure prediction using model stacking based on satellite ima...
Review of recent advances in non-invasive hemoglobin estimation
cuic standard and advanced reporting.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?

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 sayed@justetc.net 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 30. PROPERTY OVERLOADING  Property overloading only works in object context 10/9/2011 30 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 36. SPL ITERATORS  MultipleIterator  NoRewindIterator  ParentIterator  RecursiveArrayIterator  RecursiveCachingIterator  RecursiveCallbackFilterIterator  RecursiveDirectoryIterator  RecursiveFilterIterator  RecursiveIteratorIterator  RecursiveRegexIterator  RecursiveTreeIterator  RegexIterator  SimpleXMLIterator 10/9/2011 36 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 41. 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
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 44. OBJECT CLONING  To create a copy of an existing object 10/9/2011 44 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net
  • 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 sayed@justetc.net