SlideShare a Scribd company logo
1 of 41
Object-Oriented Programming with PHP
Part 3
by Nikola Bintev
Table of contents
•Static methods and properties
•Constants
•Abstraction and interfaces
•Overloading
•Object Iteration
•Object Cloning
•Serialization
•Namespaces
•Autoloading Classes
•Defining method or property as 'static' makes
them accessible without needing an
instantiation of a class
–Accessed with the double-colon (::) operator
instead of the member (->) operator
–$this is not available in static methods
–Static properties and methods can also have scope
defined – public, private or protected
•Example of static method and property
–Class can access statics with the self keyword
–Outside world accesses statics with the class
name
class A {
public static $myVariable;
public static function myPrint() {
echo self::$myVariable;
}
}
A::$myVariable = 'test';
A::myPrint();
•Constants in PHP usually are declared with the
define function
•Constants can be defined in class
–Differ from normal variables – no need for $
symbol to declare and access
–Declared with the const keyword
–Value must be supplied with the declaration
–Accessed with scope operator (::)
–Can be overridden by child classes
–Value must be constant expression, not a
variable, class member, result of operation or
function call
•Example of a class constant
class A {
const myConstant = 'value';
public function showConstant() {
echo self::myConstant;
}
}
echo A::myConstant;
$obj = new A();
$obj->showConstant();
•Classes, defined as abstract, cannot have
instances (cannot create object of this class)
–Abstract methods do not have implementation
(body) in the class
•Only signature
–The class must be inherited
–The child class must implement all abstract
methods
abstract class AbstractClass {
abstract protected function getValue();
abstract public function getValue2($prefix);
public function printOut () {
echo $this->getValue();
}
}
class Class1 extends AbstractClass {
protected function getValue (){
return "Class1";
}
public function getValue2($prefix) {
return $prefix."NAC1";
}
}
// continue from previous slide
class Class2 extends AbstractClass {
protected function getValue (){
return "Class2";
}
public function getValue2($prefix) {
return $prefix."NAC2";
}
}
$class1 = new Class1();
$class1->printOut(); // "Class1";
echo $class1->getValue2('FOO'); // FOONAC1
$class2 = new Class2();
$class2->printOut(); // "Class2";
echo $class2->getValue2('FOO'); //FOONAC2
•Object interfaces allow you to specify what
methods a child class must implement
–Declared with the interface keyword
–Similar to abstract class
–Interface can have only public methods
–No method in interface can have implementation
•Interfaces are inherited with the implements
keyword (instead of extends)
–One class may implement multiple interfaces, if
they do not have methods with same names
interface iTemplate {
public function set ($name, $value);
public function getHTML($template);
}
class Template implements iTemplate {
private $vars = array();
public function set ($name, $value) {
$this->vars[$name] = $value;
}
public function getHTML($template) {
foreach($this->vars as $name=>$value) {
$template = str_replace('{'.$name.'}', $value, $template);
}
return $template;
}
}
•Overloading in PHP provides the means to
dynamically create members and methods via
set of "magical" methods
–Invoked with interacting with members or
methods that have not been declared or are not
visible in the current scope
–All of the magic methods must be declared as
public
–None of the magic functions can be called with
arguments, passed by reference
•All overloading methods are invoked when
accessing variable or method that is not
declared or is inaccessible
•__set($name, $value) – when writing
•__get ($name) –when reading
•__isset ($name) – when calling isset() function
•__unset ($name) – when calling unset()
function
•__call ($name, $arguments) - when calling a
method
•__callStatic ($name, $arguments) – when
calling a method in a static context
–Added after PHP 5.3
–Must always be declared as static
•PHP "overloading" is a lot different from most
languages "overloading"
–Usually it means the ability to declare two
methods with different sets of parameters but
same names
•PHP provides a way for object to be iterated
trough as a list of items (array)
–foreach can be used
–By default iterates all visible properties
class A {
public $var1 = 1;
public $var2 = 2;
protected $var3 = 3;
private $var4 = 4;
function printIteration () {
foreach ($this as $key=>$val)
echo "$key : $valn";
}
}
$obj = new A();
// this prints only the public properties
foreach ($obj as $key=>$val)
echo "$key : $val n";
// this prints protected and private too
$obj->printIteration ();
•To take object iteration a step further, you can
implement one of the PHP interfaces
–Provided by the Standard PHP Library
–Allows the objects to decide what to show and
what not
–Some provided interfaces:
•Iterator – very long to implement but provides dull
features
•IteratorAggregate – simple version of Iterator interface
•ArrayIterator, DirectoryIterator, etc.
•An object can be cloned with the clone
keyword
–This will create new independent object
•Creating a copy of an object with fully
replicated properties is not always the wanted
behavior
$obj1 = new A();
$obj2 = clone $obj1;
–A class can implement the magic method __clone
which is called for the newly created object
–Called "clone constructor"
–Allows necessary changes to be done on the
newly created object
–Example: Object holding reference to resource –
the new object must have new references, instead
of copies
–Example: Object holding reference to another
object that must not be copied
class A {
private $fileName;
private $fp = null;
public function open ($file) {
$this->fileName = $file;
$this->fp = fopen ($file, 'r');
}
public function close () {
if ($this->fp) {
fclose($this->fp);
$this->fp = null;
}
}
public function __clone () {
// reopen the file for the new object
if ($this->fp)
$this->fp= fopen($this->file, 'r');
}
}
•Serializing is the process of transforming an
object into a string, that can be stored
–This string can be used to restore the object
–Useful for storing objects in session data
–Saves only properties values and class names – no
methods
–PHP provides the serialize and unserialize
functions
•serialize ($object) – returns string,
representing the object
•unserialize ($string) – returns new object, that
is restored from the serialized string
•unserialize requires the class to be defined
before calling it
class A {
public $var;
public function myPrint () { echo $this->var; }
}
$obj = new A;
$obj->var = 10;
$data = serialize ($obj);
// store $data in a file
file_put_contents ('data.dat', $data);
// …
// in a new page:
$data = file_get_contents ('data.dat');
$obj = unserialize ($data);
$obj->myPrint (); // prints 10
•Before serializing and after unserializing PHP
checks if the class has the magic methods
__sleep and __wakeup
–__sleep allows the class to commit pending data,
cleanup or define what needs to be stored if the
object is very large
•Should return array with names of properties to be
stored
–__wakeup allows the class to restore connections
or other re-initialization
class A {
public $var;
public function myPrint () { echo $this->var; }
}
$obj = new A;
$obj->var = 10;
$data = serialize ($obj);
// store $data in a file
file_put_contents ('data.dat', $data);
// …
// in a new page:
$data = file_get_contents ('data.dat');
$obj = unserialize ($data);
$obj->myPrint (); // prints 10
// continues from previous slide
public function __sleep () {
// skip serializing $link
return array ('server', 'user',
'pass', 'db');
}
public function __wakeup () {
$this->connect();
}
}
•Namespaces in PHP are designed to resolve
scope problems in large PHP libraries
–Simplify development in object oriented
environment
–Clears the code – no long classes names
•In PHP all classes declarations are global
–Namespaces allow to have two classes with same
name
–Old approach was adding prefixes to class names
(Like the mysql_* functions)
•Available since PHP 5.3
•Namespaces are declared with the namespace
keyword
–Should be always in the beginning of the file
–Namespace can contain classes, constants,
functions but no free code
<?
namespace Project;
class MyTemplate { … }
function print_headers () { … }
…
?>
•Classes, function and etc. in a namespace are
automatically prefixed with the name of the
namespace
–So in the example we would use
Project::MyTemplate to access the class
–Constants in namespaces are defined with const
keyword, not with define
// file Project.php
namespace Project;
// declare base classes and etc.
…
// file project/db.php;
namespace Project::DB;
// declare DB interface for work with database
…
// file project/db/mysql.php
namespace Project::DB::MySQL;
// implement the DB interface for mysql
…
// file project/db/oracle.php
Namespace Project::DB::Oracle;
// implement the DB interface for Oracle
…
// somewhere in the project
require "project/db/mysql.php";
$a = new Project::DB::MySQL::Connection();
Project::DB::MySQL::connect();
•The use operator allows aliasing namespaces
names
–If new name is not specified the namespace is
imported in the current context (global
namespace)
•Even if aliased, every class and function can be
accessed at any time by full name
use Project::DB::MySQL as DBLink;
$x = new DBLink::Connection();
DBLink::connect();
use Project::DB::MySQL;
$x = new MySQL::Connection();
MySQL::connect();
•By default PHP works in the global namespace
–All the project is executed there
–Method from the global namespace can be
referred to with empty scope operator
namespace Project::Files;
// this is the Project::Files::fopen function
function fopen (…) {
…
$f = ::fopen (…); // calls global fopen
…
}
•Usually every class is declared in separate file
–In big object oriented projects on every page you
may have to include dozens of files
–You can define __autoload function that is called
when trying to access class that is not defined
•It can include the necessary file for the class
•Exceptions, thrown in __autoload cannot be
caught and result in fatal error
<?
function __autoload ($class_name) {
$name = "includes/".$class_name.".inc.php";
if (file_exists ($name))
include $name;
else
echo 'Class not found';
}
?>
•Example:
class A {
public static function whoami () {
echo __CLASS__;
}
public static function test () {
self::whoami();
}
}
class B extends A {
public static function whoami () {
echo __CLASS__;
}
}
B::test(); // outputs 'A' ?!
•PHP 5.3 introduces the late static binding
which allows to reference the called class in
context of static
–In practice – this adds static:: scope
–So if in the above example we use
static::whoami() in the test() method body we get
output 'B'
•Resources
–http://php-uroci.devbg.org/
–http://academy.telerik.com/
–http://www.codecademy.com/
Exercises [0]
1.Define class Student that holds information
about students: full name, course, specialty,
university, email, phone.
2.Define constructor for the class Student that
takes full name as parameter.
3.Add a method in the class Student for
displaying all information about the student.
4.Create two students and print their
information.
5.Create an interface IAnimal that represents
an animal from the real world. Define the
Exercises [1]
1.Create an abstract class Cat that has Name
and implements the interface IAnimal and
introduces abstract method printInfo().
2.Inherit from the base abstract class Cat and
create subclasses Kitten and Tomcat. These
classes should fully implement the IAnimal
interface and define an implementation for the
abstract methods from the class Cat.
3.Create class Dog that implements IAnimal.
4.Write a class TestAnimals that creates an
array of animals: Tomcat, Kitten, Dog and calls
Exercises [2]
1.We are given a school. In the school there are
classes of students. Each class has a set of
teachers. Each teacher teaches a set of
disciplines. Students have name and unique
class number. Classes have unique text
identifier. Teachers have name and title.
Disciplines have name, number of lectures and
number of exercises.
Define classes for the school (School, Class,
Student, Teacher, Discipline). Keep the member
fields private. Add constructors and accessor

More Related Content

What's hot

What's hot (20)

Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHP
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in php
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Oop in-php
Oop in-phpOop in-php
Oop in-php
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine Project
 
Introduction to php oop
Introduction to php oopIntroduction to php oop
Introduction to php oop
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
SQL Devlopment for 10 ppt
SQL Devlopment for 10 pptSQL Devlopment for 10 ppt
SQL Devlopment for 10 ppt
 
PHP Classes and OOPS Concept
PHP Classes and OOPS ConceptPHP Classes and OOPS Concept
PHP Classes and OOPS Concept
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5
 
Declarative Data Modeling in Python
Declarative Data Modeling in PythonDeclarative Data Modeling in Python
Declarative Data Modeling in Python
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
 
Oops in php
Oops in phpOops in php
Oops in php
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
PHP OOP
PHP OOPPHP OOP
PHP OOP
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
 

Similar to FFW Gabrovo PMG - PHP OOP Part 3

Advanced php
Advanced phpAdvanced php
Advanced phphamfu
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxShaownRoy1
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Alena Holligan
 
PHP-05-Objects.ppt
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.pptrani marri
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeDhivyaa C.R
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpAlena Holligan
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Bozhidar Boshnakov
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Alena Holligan
 
Demystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPDemystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPAlena Holligan
 
Object oriented programming in php
Object oriented programming in phpObject oriented programming in php
Object oriented programming in phpAashiq Kuchey
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHPwahidullah mudaser
 
Demystifying Object-Oriented Programming - Midwest PHP
Demystifying Object-Oriented Programming - Midwest PHPDemystifying Object-Oriented Programming - Midwest PHP
Demystifying Object-Oriented Programming - Midwest PHPAlena Holligan
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classesKumar
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Alena Holligan
 

Similar to FFW Gabrovo PMG - PHP OOP Part 3 (20)

Advanced php
Advanced phpAdvanced php
Advanced php
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16
 
PHP-05-Objects.ppt
PHP-05-Objects.pptPHP-05-Objects.ppt
PHP-05-Objects.ppt
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphp
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)
 
Only oop
Only oopOnly oop
Only oop
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
 
OOPs Concept
OOPs ConceptOOPs Concept
OOPs Concept
 
Demystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPDemystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHP
 
Object oriented programming in php
Object oriented programming in phpObject oriented programming in php
Object oriented programming in php
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHP
 
Demystifying Object-Oriented Programming - Midwest PHP
Demystifying Object-Oriented Programming - Midwest PHPDemystifying Object-Oriented Programming - Midwest PHP
Demystifying Object-Oriented Programming - Midwest PHP
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classes
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017
 

More from Toni Kolev

FFW Gabrovo PMG - jQuery
FFW Gabrovo PMG - jQueryFFW Gabrovo PMG - jQuery
FFW Gabrovo PMG - jQueryToni Kolev
 
FFW Gabrovo PMG - JavaScript 2
FFW Gabrovo PMG - JavaScript 2FFW Gabrovo PMG - JavaScript 2
FFW Gabrovo PMG - JavaScript 2Toni Kolev
 
FFW Gabrovo PMG - JavaScript 1
FFW Gabrovo PMG - JavaScript 1FFW Gabrovo PMG - JavaScript 1
FFW Gabrovo PMG - JavaScript 1Toni Kolev
 
FFW Gabrovo PMG - CSS
FFW Gabrovo PMG - CSSFFW Gabrovo PMG - CSS
FFW Gabrovo PMG - CSSToni Kolev
 
FFW Gabrovo PMG - Development Process
FFW Gabrovo PMG - Development ProcessFFW Gabrovo PMG - Development Process
FFW Gabrovo PMG - Development ProcessToni Kolev
 
FFW Gabrovo PMG - HTML
FFW Gabrovo PMG - HTMLFFW Gabrovo PMG - HTML
FFW Gabrovo PMG - HTMLToni Kolev
 

More from Toni Kolev (6)

FFW Gabrovo PMG - jQuery
FFW Gabrovo PMG - jQueryFFW Gabrovo PMG - jQuery
FFW Gabrovo PMG - jQuery
 
FFW Gabrovo PMG - JavaScript 2
FFW Gabrovo PMG - JavaScript 2FFW Gabrovo PMG - JavaScript 2
FFW Gabrovo PMG - JavaScript 2
 
FFW Gabrovo PMG - JavaScript 1
FFW Gabrovo PMG - JavaScript 1FFW Gabrovo PMG - JavaScript 1
FFW Gabrovo PMG - JavaScript 1
 
FFW Gabrovo PMG - CSS
FFW Gabrovo PMG - CSSFFW Gabrovo PMG - CSS
FFW Gabrovo PMG - CSS
 
FFW Gabrovo PMG - Development Process
FFW Gabrovo PMG - Development ProcessFFW Gabrovo PMG - Development Process
FFW Gabrovo PMG - Development Process
 
FFW Gabrovo PMG - HTML
FFW Gabrovo PMG - HTMLFFW Gabrovo PMG - HTML
FFW Gabrovo PMG - HTML
 

Recently uploaded

定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
VIP Kolkata Call Girl Dum Dum 👉 8250192130 Available With Room
VIP Kolkata Call Girl Dum Dum 👉 8250192130  Available With RoomVIP Kolkata Call Girl Dum Dum 👉 8250192130  Available With Room
VIP Kolkata Call Girl Dum Dum 👉 8250192130 Available With Roomdivyansh0kumar0
 
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts servicesonalikaur4
 
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一3sw2qly1
 
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls KolkataVIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607dollysharma2066
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一Fs
 
How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)Damian Radcliffe
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Denver Web Design brochure for public viewing
Denver Web Design brochure for public viewingDenver Web Design brochure for public viewing
Denver Web Design brochure for public viewingbigorange77
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
Complet Documnetation for Smart Assistant Application for Disabled Person
Complet Documnetation   for Smart Assistant Application for Disabled PersonComplet Documnetation   for Smart Assistant Application for Disabled Person
Complet Documnetation for Smart Assistant Application for Disabled Personfurqan222004
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一Fs
 
Russian Call girls in Dubai +971563133746 Dubai Call girls
Russian  Call girls in Dubai +971563133746 Dubai  Call girlsRussian  Call girls in Dubai +971563133746 Dubai  Call girls
Russian Call girls in Dubai +971563133746 Dubai Call girlsstephieert
 

Recently uploaded (20)

定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
VIP Kolkata Call Girl Dum Dum 👉 8250192130 Available With Room
VIP Kolkata Call Girl Dum Dum 👉 8250192130  Available With RoomVIP Kolkata Call Girl Dum Dum 👉 8250192130  Available With Room
VIP Kolkata Call Girl Dum Dum 👉 8250192130 Available With Room
 
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
 
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
 
sasti delhi Call Girls in munirka 🔝 9953056974 🔝 escort Service-
sasti delhi Call Girls in munirka 🔝 9953056974 🔝 escort Service-sasti delhi Call Girls in munirka 🔝 9953056974 🔝 escort Service-
sasti delhi Call Girls in munirka 🔝 9953056974 🔝 escort Service-
 
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls KolkataVIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Call Girls In South Ex 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICECall Girls In South Ex 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In South Ex 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
 
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
 
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
定制(Lincoln毕业证书)新西兰林肯大学毕业证成绩单原版一比一
 
How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
 
Denver Web Design brochure for public viewing
Denver Web Design brochure for public viewingDenver Web Design brochure for public viewing
Denver Web Design brochure for public viewing
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
Complet Documnetation for Smart Assistant Application for Disabled Person
Complet Documnetation   for Smart Assistant Application for Disabled PersonComplet Documnetation   for Smart Assistant Application for Disabled Person
Complet Documnetation for Smart Assistant Application for Disabled Person
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
 
Call Girls Service Dwarka @9999965857 Delhi 🫦 No Advance VVIP 🍎 SERVICE
Call Girls Service Dwarka @9999965857 Delhi 🫦 No Advance  VVIP 🍎 SERVICECall Girls Service Dwarka @9999965857 Delhi 🫦 No Advance  VVIP 🍎 SERVICE
Call Girls Service Dwarka @9999965857 Delhi 🫦 No Advance VVIP 🍎 SERVICE
 
Russian Call girls in Dubai +971563133746 Dubai Call girls
Russian  Call girls in Dubai +971563133746 Dubai  Call girlsRussian  Call girls in Dubai +971563133746 Dubai  Call girls
Russian Call girls in Dubai +971563133746 Dubai Call girls
 

FFW Gabrovo PMG - PHP OOP Part 3

  • 1. Object-Oriented Programming with PHP Part 3 by Nikola Bintev
  • 2. Table of contents •Static methods and properties •Constants •Abstraction and interfaces •Overloading •Object Iteration •Object Cloning •Serialization •Namespaces •Autoloading Classes
  • 3. •Defining method or property as 'static' makes them accessible without needing an instantiation of a class –Accessed with the double-colon (::) operator instead of the member (->) operator –$this is not available in static methods –Static properties and methods can also have scope defined – public, private or protected
  • 4. •Example of static method and property –Class can access statics with the self keyword –Outside world accesses statics with the class name class A { public static $myVariable; public static function myPrint() { echo self::$myVariable; } } A::$myVariable = 'test'; A::myPrint();
  • 5. •Constants in PHP usually are declared with the define function •Constants can be defined in class –Differ from normal variables – no need for $ symbol to declare and access –Declared with the const keyword –Value must be supplied with the declaration –Accessed with scope operator (::) –Can be overridden by child classes –Value must be constant expression, not a variable, class member, result of operation or function call
  • 6. •Example of a class constant class A { const myConstant = 'value'; public function showConstant() { echo self::myConstant; } } echo A::myConstant; $obj = new A(); $obj->showConstant();
  • 7. •Classes, defined as abstract, cannot have instances (cannot create object of this class) –Abstract methods do not have implementation (body) in the class •Only signature –The class must be inherited –The child class must implement all abstract methods
  • 8. abstract class AbstractClass { abstract protected function getValue(); abstract public function getValue2($prefix); public function printOut () { echo $this->getValue(); } } class Class1 extends AbstractClass { protected function getValue (){ return "Class1"; } public function getValue2($prefix) { return $prefix."NAC1"; } }
  • 9. // continue from previous slide class Class2 extends AbstractClass { protected function getValue (){ return "Class2"; } public function getValue2($prefix) { return $prefix."NAC2"; } } $class1 = new Class1(); $class1->printOut(); // "Class1"; echo $class1->getValue2('FOO'); // FOONAC1 $class2 = new Class2(); $class2->printOut(); // "Class2"; echo $class2->getValue2('FOO'); //FOONAC2
  • 10. •Object interfaces allow you to specify what methods a child class must implement –Declared with the interface keyword –Similar to abstract class –Interface can have only public methods –No method in interface can have implementation •Interfaces are inherited with the implements keyword (instead of extends) –One class may implement multiple interfaces, if they do not have methods with same names
  • 11. interface iTemplate { public function set ($name, $value); public function getHTML($template); } class Template implements iTemplate { private $vars = array(); public function set ($name, $value) { $this->vars[$name] = $value; } public function getHTML($template) { foreach($this->vars as $name=>$value) { $template = str_replace('{'.$name.'}', $value, $template); } return $template; } }
  • 12. •Overloading in PHP provides the means to dynamically create members and methods via set of "magical" methods –Invoked with interacting with members or methods that have not been declared or are not visible in the current scope –All of the magic methods must be declared as public –None of the magic functions can be called with arguments, passed by reference
  • 13. •All overloading methods are invoked when accessing variable or method that is not declared or is inaccessible •__set($name, $value) – when writing •__get ($name) –when reading •__isset ($name) – when calling isset() function •__unset ($name) – when calling unset() function
  • 14. •__call ($name, $arguments) - when calling a method •__callStatic ($name, $arguments) – when calling a method in a static context –Added after PHP 5.3 –Must always be declared as static •PHP "overloading" is a lot different from most languages "overloading" –Usually it means the ability to declare two methods with different sets of parameters but same names
  • 15. •PHP provides a way for object to be iterated trough as a list of items (array) –foreach can be used –By default iterates all visible properties
  • 16. class A { public $var1 = 1; public $var2 = 2; protected $var3 = 3; private $var4 = 4; function printIteration () { foreach ($this as $key=>$val) echo "$key : $valn"; } } $obj = new A(); // this prints only the public properties foreach ($obj as $key=>$val) echo "$key : $val n"; // this prints protected and private too $obj->printIteration ();
  • 17. •To take object iteration a step further, you can implement one of the PHP interfaces –Provided by the Standard PHP Library –Allows the objects to decide what to show and what not –Some provided interfaces: •Iterator – very long to implement but provides dull features •IteratorAggregate – simple version of Iterator interface •ArrayIterator, DirectoryIterator, etc.
  • 18. •An object can be cloned with the clone keyword –This will create new independent object •Creating a copy of an object with fully replicated properties is not always the wanted behavior $obj1 = new A(); $obj2 = clone $obj1;
  • 19. –A class can implement the magic method __clone which is called for the newly created object –Called "clone constructor" –Allows necessary changes to be done on the newly created object –Example: Object holding reference to resource – the new object must have new references, instead of copies –Example: Object holding reference to another object that must not be copied
  • 20. class A { private $fileName; private $fp = null; public function open ($file) { $this->fileName = $file; $this->fp = fopen ($file, 'r'); } public function close () { if ($this->fp) { fclose($this->fp); $this->fp = null; } } public function __clone () { // reopen the file for the new object if ($this->fp) $this->fp= fopen($this->file, 'r'); } }
  • 21. •Serializing is the process of transforming an object into a string, that can be stored –This string can be used to restore the object –Useful for storing objects in session data –Saves only properties values and class names – no methods –PHP provides the serialize and unserialize functions
  • 22. •serialize ($object) – returns string, representing the object •unserialize ($string) – returns new object, that is restored from the serialized string •unserialize requires the class to be defined before calling it
  • 23. class A { public $var; public function myPrint () { echo $this->var; } } $obj = new A; $obj->var = 10; $data = serialize ($obj); // store $data in a file file_put_contents ('data.dat', $data); // … // in a new page: $data = file_get_contents ('data.dat'); $obj = unserialize ($data); $obj->myPrint (); // prints 10
  • 24. •Before serializing and after unserializing PHP checks if the class has the magic methods __sleep and __wakeup –__sleep allows the class to commit pending data, cleanup or define what needs to be stored if the object is very large •Should return array with names of properties to be stored –__wakeup allows the class to restore connections or other re-initialization
  • 25. class A { public $var; public function myPrint () { echo $this->var; } } $obj = new A; $obj->var = 10; $data = serialize ($obj); // store $data in a file file_put_contents ('data.dat', $data); // … // in a new page: $data = file_get_contents ('data.dat'); $obj = unserialize ($data); $obj->myPrint (); // prints 10
  • 26. // continues from previous slide public function __sleep () { // skip serializing $link return array ('server', 'user', 'pass', 'db'); } public function __wakeup () { $this->connect(); } }
  • 27. •Namespaces in PHP are designed to resolve scope problems in large PHP libraries –Simplify development in object oriented environment –Clears the code – no long classes names •In PHP all classes declarations are global –Namespaces allow to have two classes with same name –Old approach was adding prefixes to class names (Like the mysql_* functions) •Available since PHP 5.3
  • 28. •Namespaces are declared with the namespace keyword –Should be always in the beginning of the file –Namespace can contain classes, constants, functions but no free code <? namespace Project; class MyTemplate { … } function print_headers () { … } … ?>
  • 29. •Classes, function and etc. in a namespace are automatically prefixed with the name of the namespace –So in the example we would use Project::MyTemplate to access the class –Constants in namespaces are defined with const keyword, not with define
  • 30. // file Project.php namespace Project; // declare base classes and etc. … // file project/db.php; namespace Project::DB; // declare DB interface for work with database … // file project/db/mysql.php namespace Project::DB::MySQL; // implement the DB interface for mysql … // file project/db/oracle.php Namespace Project::DB::Oracle; // implement the DB interface for Oracle … // somewhere in the project require "project/db/mysql.php"; $a = new Project::DB::MySQL::Connection(); Project::DB::MySQL::connect();
  • 31. •The use operator allows aliasing namespaces names –If new name is not specified the namespace is imported in the current context (global namespace) •Even if aliased, every class and function can be accessed at any time by full name use Project::DB::MySQL as DBLink; $x = new DBLink::Connection(); DBLink::connect(); use Project::DB::MySQL; $x = new MySQL::Connection(); MySQL::connect();
  • 32. •By default PHP works in the global namespace –All the project is executed there –Method from the global namespace can be referred to with empty scope operator namespace Project::Files; // this is the Project::Files::fopen function function fopen (…) { … $f = ::fopen (…); // calls global fopen … }
  • 33. •Usually every class is declared in separate file –In big object oriented projects on every page you may have to include dozens of files –You can define __autoload function that is called when trying to access class that is not defined •It can include the necessary file for the class
  • 34. •Exceptions, thrown in __autoload cannot be caught and result in fatal error <? function __autoload ($class_name) { $name = "includes/".$class_name.".inc.php"; if (file_exists ($name)) include $name; else echo 'Class not found'; } ?>
  • 35. •Example: class A { public static function whoami () { echo __CLASS__; } public static function test () { self::whoami(); } } class B extends A { public static function whoami () { echo __CLASS__; } } B::test(); // outputs 'A' ?!
  • 36. •PHP 5.3 introduces the late static binding which allows to reference the called class in context of static –In practice – this adds static:: scope –So if in the above example we use static::whoami() in the test() method body we get output 'B'
  • 38.
  • 39. Exercises [0] 1.Define class Student that holds information about students: full name, course, specialty, university, email, phone. 2.Define constructor for the class Student that takes full name as parameter. 3.Add a method in the class Student for displaying all information about the student. 4.Create two students and print their information. 5.Create an interface IAnimal that represents an animal from the real world. Define the
  • 40. Exercises [1] 1.Create an abstract class Cat that has Name and implements the interface IAnimal and introduces abstract method printInfo(). 2.Inherit from the base abstract class Cat and create subclasses Kitten and Tomcat. These classes should fully implement the IAnimal interface and define an implementation for the abstract methods from the class Cat. 3.Create class Dog that implements IAnimal. 4.Write a class TestAnimals that creates an array of animals: Tomcat, Kitten, Dog and calls
  • 41. Exercises [2] 1.We are given a school. In the school there are classes of students. Each class has a set of teachers. Each teacher teaches a set of disciplines. Students have name and unique class number. Classes have unique text identifier. Teachers have name and title. Disciplines have name, number of lectures and number of exercises. Define classes for the school (School, Class, Student, Teacher, Discipline). Keep the member fields private. Add constructors and accessor

Editor's Notes

  1. 2
  2. 3
  3. 4
  4. 5
  5. 6
  6. 7
  7. 8
  8. 9
  9. 10
  10. 11
  11. 12
  12. 13
  13. 14
  14. 15
  15. 16
  16. 17
  17. 18
  18. 19
  19. 20
  20. 21
  21. 22
  22. 23
  23. 24
  24. 25
  25. 26
  26. 27
  27. 28
  28. 29
  29. 30
  30. 31
  31. 32
  32. 33
  33. 34
  34. 35
  35. 36
  36. 37
  37. 39
  38. 40
  39. 41