SlideShare a Scribd company logo
1 of 56
http://xkcd.com/327/
Remember ourRemember our last lecturelast lecture??
Encapsulation, Inheritance, PolymorphismEncapsulation, Inheritance, Polymorphism
• Data membersData members
• MethodsMethods
Object OrientationObject Orientation

PHPisan Object-Oriented programming
language

Fundamental feature of OO isthe classclass

PHPclassessupport
− Encapsulation
− Inheritance
− Polymorphism
What is aWhat is a ClassClass??
ClassesClasses

SophisticatedSophisticated ‘variable types’‘variable types’

Data variables (data membersdata members) and functions
(methodsmethods) are wrapped up in a class. Collectively,
data members and methods are referred to as classclass
membersmembers.
An instanceinstance of a classof a class is known as an objectobject.
//defining a new class named Robot
class RobotRobot {{
//place class members here...
}}
Instantiating a class usingInstantiating a class using newnew

Once a classhasbeen created, any numberany number of
object instancesof that classcan be created.

$dogRobot = newnew Robot()Robot();

To invoke methods:
− object->->method()

e.g.
<?php
....
$dogRobot = newnew Robot()Robot();
$dogRobot ->crawlWeb();
$dogRobot -> play();
echo $dogRobot ->talk();
...
?>
<?php
class Person {
private $strFirstname = “Napoleon";
private $strSurname = “Reyes";
function getFirstname() {
return $this->strFirstname;
}
function getSurname() {
return $this->strSurname;
}
}
// outside the class definition
$obj = newnew Person; // an object of type Person
echo "<p>Firstname: " . $obj->getFirstname() . "</p>";
echo "<p>Surname: " . $obj->getSurname() . "</p>";
?>
Defining classesDefining classes
Data members
Methods
Example16-1.php
EncapsulationEncapsulation
Data membersData members are normally set inaccessible from outside
the class (as well as certain types of methodsmethods) protecting
them from the rest of the script and other classes.
This protection of class members is known as
encapsulationencapsulation.
 e.g.
<?php
....
$dogRobot = newnew Robot()Robot();
$dogRobot ->crawlWeb();
$dogRobot -> play();
echo $dogRobot ->talk();
...
?>
InheritanceInheritance
New classesNew classes can be defined very similar to existing onesexisting ones.
All we need to do is specify the differencesdifferences between the
new class and the existing one.
Data membersData members and methodsmethods which are notnot defined as
being privateprivate to a class are automatically accessible by
the new class.
This is known as inheritanceinheritance and is an extremely powerful
and useful programming tool.
PolymorphismPolymorphism
A concept where a number of related classesrelated classes all have a
methodmethod, which shares the same name.
class Fish { draw()...draw()... //draws a fish//draws a fish...... }}
class Dog { draw()...draw()... //draws a dog//draws a dog...... }}
class Bird { draw()...draw()... //draws a bird//draws a bird...... }}
We can write a generic code that can operate on anycan operate on any of
these classes, invoking the appropriate draw()draw() method
based on certain conditions.
Example:Example: Defining classesDefining classes
class ShoppingCart {
private $name; // Name of shoppershopper
private $items; // Items in our shopping cartItems in our shopping cart
public function ShoppingCartShoppingCart($inputname) {
$this->name = $inputname;
}
// Add $num articles of $artnr to the cart
public function addItemaddItem($artnr, $num) {
$this->items[$artnr] += $num;
}
// Take $num articles of $artnr out of the cart
public function removeItemremoveItem($artnr, $num) {
if ($this->items[$artnr] > $num) {
$this->items[$artnr] -= $num;
return true;
} elseif ($this->items[$artnr] == $num) {
unset($this->items[$artnr]);
return true;
} else {
return false;
}
}
}
Let’sexamine the syntax of defining a classnext...
Data members and MethodsData members and Methods
class Class1Class1 {
private $strName$strName = “A”;
private $intNumber$intNumber = 1;
function getName()Name() {
}
function getNumber()getNumber(){
}
}

We need to provide
accessor functionsto
allow usersof Class1
to accessthe privateprivate
data members:
function getName()getName(){
return $this->this->strNamestrName;
}
Isthispublicly accessible?
$this$this object pointerobject pointer

Aswith so many languages, there isa special
pointer that referencesan instance of a class:
− $this$this
function getName(){
return $this->strName;
}
function getName(){
return strName;
}
 
Invoking methodsInvoking methods inside a classinside a class
class Person{
...
function setFirstname($strSurname) {
$this->strFirstname = $strSurname;
}
function setSurname($strSurname) {
$this->strSurname = $strSurname;
}
private function display() {
echo "<p>Firstname: " . $this->strFirstname . "</p>";
echo "<p>Surname: " . $this->strSurname . "</p>";
}
function setDisplayFirstnameSurname($strFirstname, $strSurname) {
$this->$this->setFirstname($strFirstname);
$this->$this->setSurname($strSurname);
$this->$this->display();
}
}
$this->$this->functionName();
Example16-4.php
ClassesClasses
class MyClassNameMyClassName{
....methods
....data members
}

Visibility of a method
or data member:
− PublicPublic
− ProtectedProtected
− PrivatePrivate
− By defaultBy default, without
the accessspecifiers,
class membersclass members are
defined publicpublic.
PrivatePrivate Access SpecifierAccess Specifier
class MyClassNameMyClassName{
privateprivate $strFirstName;
}

privateprivate – limitsthe
visibility of the methods
and data members
only to the classthat
definesthem.
Modifying data membersModifying data members

Outside the class, trying to execute
the following:
$clMyObj->intNumber++intNumber++;

will fail!...

We need a method to accessand change
itsvalue:
function setNumber($intNumber) {
$this->intNumber = $intNumber;
}
intNumberintNumber is privateprivate
Look at the position of the dollar sign ($) – no
longer attached to the variable name
PublicPublic Access SpecifierAccess Specifier
class MyClassNameMyClassName{
publicpublic $strFirstName;
publicpublic function getFirstName()getFirstName(){
}
} 
publicpublic – class
memberscan be
accessed both withinwithin
and outsideand outside the class.
ProtectedProtected Access SpecifierAccess Specifier
Class MyClassNameMyClassName{
protectedprotected $strFirstName;
protectedprotected function getFirstName()getFirstName(){
}
}

InheritedInherited protectedprotected class membersclass members –
accessible inside a derived classderived class

Visibility ofVisibility of protectedprotected class membersclass members
outside the class definitionoutside the class definition – protected
classmembersare inaccessible.
//protected for public use, but accessible in a
derived class
PROPERTY DECLARATION
<?php
class MyClass {
public $public = 'Public';
protected $protected = 'Protected'; //protected for public use, but accessible in a derived class
private $private = 'Private';
function printHello()printHello() {
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
// outside the class definition
$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private
//...
Example:Example: Access SpecifiersAccess Specifiers




http://php.net/manual/en/language.oop5.visibility.php
<?php
//...
class MyClass2 extendsextends MyClass
{
// We can redeclare the public and protected method, but not private
// protected – ‘protected’ for public use, but accessible in a derived class
protected $protected = 'Protected2';
function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
// outside the class definition
$obj2 = new MyClass2();
echo $obj2->public; // Works
echo $obj2->private; // Undefined
echo $obj2->protected; // Fatal Error
$obj2->printHello(); // Shows Public, Protected2, Undefined
?>
Example:Example: Access SpecifiersAccess Specifiers



http://php.net/manual/en/language.oop5.visibility.php
a Derived class
METHOD DECLARATION
//OUTSIDE THE CLASS DEFINITION...
$myclass = new MyClass;
$myclass->MyPublic(); // Works
$myclass->MyProtected(); // Fatal Error
$myclass->MyPrivate(); // Fatal Error
$myclass->Foo(); // Public, Protected and Private work
//...
<?php
class MyClass
{
// Declare a public constructor
public function __construct() { }
// Declare a public method
public function MyPublic() { }
// Declare a protected method
protected function MyProtected() { }
// Declare a private method
private function MyPrivate() { }
// This is public
function Foo()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate();
}
}



http://php.net/manual/en/language.oop5.visibility.php
Example:Example: Method DeclarationMethod Declaration
class MyClass2 extendsextends MyClass
{
// This is public
function Foo2()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate(); // Fatal Error
}
}
$myclass2 = newnew MyClass2;
$myclass2->MyPublic(); // Works
$myclass2->Foo2(); // Public and Protected work, not Private
Example:Example: Method DeclarationMethod Declaration
  
http://php.net/manual/en/language.oop5.visibility.php
<?php
class MyClass
{
// Declare a public constructor
public function __construct() { }
// Declare a public method
public function MyPublic() { }
// Declare a protected method
protected function MyProtected() { }
// Declare a private method
private function MyPrivate() { }
// This is public
function Foo()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate();
}
}
$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate
// Foo::testPublic
?>
Example:Example: Method DeclarationMethod Declaration


http://php.net/manual/en/language.oop5.visibility.php
<?php
class Bar
{
public function test() {
$this->testPrivate();
$this->testPublic();
}
public function testPublic() {
echo "Bar::testPublicn";
}
private function testPrivate() {
echo "Bar::testPrivaten";
}
}
class Foo extends Bar
{
public function testPublic() {
echo "Foo::testPublicn";
}
private function testPrivate() {
echo "Foo::testPrivaten";
}
}
string(5) "hello"
Accessed the private method
Accessing Private Members of theAccessing Private Members of the
same object typesame object type

http://php.net/manual/en/language.oop5.visibility.php
<?php
class Test
{
private $foo;
public function __construct($foo)
{
$this->foo = $foo;
}
private function bar()
{
echo 'Accessed the private method.';
}
public function baz(Test $other)
{
// We can change the private property:
$other->foo = 'hello';
var_dump($other->foo);
// We can also call the private method:
$other->bar();
}
}
$test = new Test('test');
$test->baz(new Test('other'));
?>
Objectsof the same type will have accessto each others
Private and protected memberseven though they are
not the same instances.
Creating objectsCreating objects
•Instantiate classes using new keyword
–$myCart= newnew ShoppingCart(“Charlie”);
ConstructorsConstructors
–In earlier versions of PHP (< PHP5.3.3PHP5.3.3) Same as the
name of the class. This no longer holds!This no longer holds!
– (PHP5 onlyPHP5 only) declared as
•public function __construct(…)
DestructorsDestructors
–Declared as
–public function __destruct()
Latest in PHPLatest in PHP5.3.35.3.3
<?php
namespace Foo;
class Bar {
public function Bar() {
// treated as constructor in PHP 5.3.0-5.3.2
// treated as regular method in PHP 5.3.3
}
}
?>
22 Sept. 2010
ConstructorsConstructors

A constructorconstructor isa function that does
initializationswhen the classisinstantiated
function __construct(__construct($intNumber, $strName)){
$this->set_intNumber($intNumber);
$this->set_strName($strName);
$this->printInit();//use thismethod
}
ConstructorsConstructors

Default argumentsDefault arguments
function __construct ($strName = “A”, $intNumber=0) {
$this->set_intNumber($int_Number);
$this->set_strName($str_Name);
}

Instantiating a classwithout parameterswill
make use of the default values
Another Example:Another Example: ConstructorsConstructors
<?php
class vehiclevehicle {
private $strDescription;
function getDescription() {
return $this->strDescription;
}
function setDescription($strDescription) {
$this->strDescription = $strDescription;
}
function __construct ($strDescription) {
$this->strDescription = $strDescription;
}
}
?>
vehicle.php
Another Example:Another Example: ConstructorsConstructors
<?php
require_once("vehicle.php");
$objBike = new vehicle("Bicycle");
echo "<p>Vehicle: " . $objBike->getDescription() . "</p>";
?>
example16-7.php
DestructorsDestructors

Called when objectsare destroyed – free up
memory

e.g.:
function __destruct () {
echo “freeing up memory, destroying thisobject... <br>”;
}
This sample code above simply informs us that the object is
being destroyed already.
Objects as variablesObjects as variables

Can be used in arrays

Can be passed to functions

Passed as referencePassed as reference all the time (PHP 55)

e.g.:
function test1($objClass1){
$objClass1->set_intName(“B”);
}

No need to use && in the formal parameterin the formal parameter
definition.definition. It isalwayspassed by reference.
Arrays and objectsArrays and objects
<?php
function __autoload($class_name) {
require_once $class_name . '.php';
}
$objSimon = new revisedperson("Simon", "Stobart");
$objLiz = new revisedperson("Liz", "Hall");
$objIan = new revisedperson("Ian", "Walker");
$objBilly = new revisedperson("Billy", "Lee");
$objHayley = new revisedperson("Hayley", "West");
$arrPeople$arrPeople = array(array($objSimon, $objLiz, $objIan, $objBilly, $objHayley));
foreach($arrPeople$arrPeople as $objThePerson){
echo($objThePerson->->display()display());
}
?>
The function display()display() is common to all array elements
(elements = objects in this example).
example16-9.php
Multiple Object InstancesMultiple Object Instances
<?php
$cart1 = new ShoppingCart(“Joe Bloggs”);
$cart1->addItem("10", 1);
$cart2 = new ShoppingCart(“Fred Smith”);
$cart2->addItem("0815", 3);
?>
Example:Example: PolymorphismPolymorphism
<?php
function __autoload($class_name) {
require_once $class_name . '.php';
}
$objRectangle = new rectangle(100,50, "rectangle.gif");
$objSquare = new square(100, "square.gif");
$objTriangle = new triangle(50,100, "triangle.gif");
$objEllipse = new ellipse(50,100, "ellipse.gif");
$arrShapes = array ($objRectangle,$objSquare,$objTriangle,$objEllipse);
foreach ($arrShapes as $objShape){
$objShape->display();
$objShape->area();
}
?>
The functions area() and display() are common to all array
elements, but executes a different formula for each type of object.
Example17-5.php
• Recommended: Create one PHP
source file per classdefinition.
• Thisaidsclassreuse and script clarity.
Remember these PHP Constructs?Remember these PHP Constructs?
• require(….)require(….)
− Includesfile specified, terminatesterminates on errors
• include(…)include(…)
− Includesfile specified, gives warningwarning on errors
• require_once(….)require_once(….)
− Includesfile specified only if it hasnot already been
included, terminatesterminates on errors
• include_once(….)include_once(….)
− Includesfile specified only if it hasnot already been
included, gives warningwarning on errors
Example16-6.php

Really useful but would require you to write a long list of include() or require() statements
at the beginning of each script, one for each class. In PHP5, this is no longer
necessary. You may define an __autoload function!
functionfunction __autoload()__autoload()
• The function is invoked automatically each time a class is
required but has not been defined.
• We can insert this function into our script:
Example16-7.php
function __autoload__autoload($class_name) {
require_oncerequire_once $class_name . '.php';
}
Note: Class_name = File_name
functionfunction __autoload()__autoload()
Example16-7.php
<?php
function __autoload__autoload($class_name) {
require_once $class_name . '.php';
}
$objSimon = newnew person;
$objSimon->setDisplayFirstnameSurname(“Napoleon", “Reyes");
$objBike = newnew vehicle("Bicycle");
echo "<p>Vehicle: " . $objBike->getDescription() . "</p>";
?>
Classdefinition comesfrom
another file.
ExceptionsExceptions
Like all good OO languages, PHP5 supports the exception
mechanism for trapping and handling “unexpected conditionsunexpected conditions”
Note: not all exceptions are necessarily errors
Exceptions not supported in PHP4
classclass MyExceptionMyException extendsextends Exception {{
// Redefine the exception so message isn't optional
public function __construct($message, $code = 0) {
// some code
// make sure everything is assigned properly
parent::__construct($message, $code);
}
// custom string representation of object
public function __toString() {
return __CLASS__ .. ": $this->messagen";
}
public function customFunction() {
echo "A Custom function for this type of exceptionn";
}
}}
Extend the built-in PHP Exception class with your ownExtend the built-in PHP Exception class with your own
exceptions (as in Java)exceptions (as in Java)
ExceptionsExceptions
<?php
Throw new MyExceptionMyException("Message to display");
?>
To generate an exception
Objects can...Objects can...

Invoke another

Be embedded within another object

Support for:
− Inheritance
− Scope resolution ( :::: operator)
− Classabstraction (define a classthat doesnot
instantiate, use “abstractabstract classclass classnameclassname” )
− Polymorphism (same function nameswith different
data / behaviour)
− '====‘ to check if two object have the same attributesand values
− '======‘ to check if two objectsare the same instance of the same class
Advanced OO in PHPAdvanced OO in PHP

PHP5 hasrich OO support (similar to the Java model)
− Single inheritance (multiple inheritance not allowed)
− Abstract classesand methods
− Interfaces

PHPisa reflective programming language
− Namesof functions/classesto be invoked do not have to be hard
wired

See also documentation at www.php.netwww.php.net
Reflection-Oriented ProgrammingReflection-Oriented Programming
// without reflection// without reflection
$Foo = new Foo();
$Foo->hello();
// with reflection// with reflection
$f = new ReflectionClassReflectionClass("Foo");
$m = $f->getMethod("hello");
$m->invoke( $f->newInstance() );
Normally, instructions are
executed and data is
processed; however, in some
languages, programs can
also treat instructions asinstructions as
datadata and therefore make
reflective modifications.
http://en.wikipedia.org/wiki/Reflection_(computer_science)
Program execution could
be modified at run-time.
New in PHP, not properly
documented yet!
http://nz2.php.net/manual/en/reflectionclass.newinstance.php
For a complete reference
http://www.php.net

More Related Content

What's hot (20)

OOP in PHP
OOP in PHPOOP in PHP
OOP in PHP
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 
PHP Classes and OOPS Concept
PHP Classes and OOPS ConceptPHP Classes and OOPS Concept
PHP Classes and OOPS Concept
 
Architecture logicielle #3 : object oriented design
Architecture logicielle #3 : object oriented designArchitecture logicielle #3 : object oriented design
Architecture logicielle #3 : object oriented design
 
Lightning talk
Lightning talkLightning talk
Lightning talk
 
Doctrator Symfony Live 2011 San Francisco
Doctrator Symfony Live 2011 San FranciscoDoctrator Symfony Live 2011 San Francisco
Doctrator Symfony Live 2011 San Francisco
 
Oop in-php
Oop in-phpOop in-php
Oop in-php
 
PHP OOP
PHP OOPPHP OOP
PHP OOP
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Anonymous Classes: Behind the Mask
Anonymous Classes: Behind the MaskAnonymous Classes: Behind the Mask
Anonymous Classes: Behind the Mask
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Lecture18
Lecture18Lecture18
Lecture18
 
Unidad o informatica en ingles
Unidad o informatica en inglesUnidad o informatica en ingles
Unidad o informatica en ingles
 
Jscript part2
Jscript part2Jscript part2
Jscript part2
 
Defining classes-part-i-constructors-properties
Defining classes-part-i-constructors-propertiesDefining classes-part-i-constructors-properties
Defining classes-part-i-constructors-properties
 
Python lecture 8
Python lecture 8Python lecture 8
Python lecture 8
 
Xtext Eclipse Con
Xtext Eclipse ConXtext Eclipse Con
Xtext Eclipse Con
 
SQL Devlopment for 10 ppt
SQL Devlopment for 10 pptSQL Devlopment for 10 ppt
SQL Devlopment for 10 ppt
 
Cfphp Zce 01 Basics
Cfphp Zce 01 BasicsCfphp Zce 01 Basics
Cfphp Zce 01 Basics
 

Viewers also liked

Object Oriented Programming for WordPress Plugin Development
Object Oriented Programming for WordPress Plugin DevelopmentObject Oriented Programming for WordPress Plugin Development
Object Oriented Programming for WordPress Plugin Developmentmtoppa
 
Plan anticorrupcion la_pintada_version 1.0
Plan anticorrupcion la_pintada_version 1.0Plan anticorrupcion la_pintada_version 1.0
Plan anticorrupcion la_pintada_version 1.0HerreraWilly
 
Doron yablekoviz_gastro_0111
Doron yablekoviz_gastro_0111Doron yablekoviz_gastro_0111
Doron yablekoviz_gastro_0111doctors only
 
Stanbic ibtc annual report 2009
Stanbic ibtc annual report 2009Stanbic ibtc annual report 2009
Stanbic ibtc annual report 2009Michael Olafusi
 
on the evolution of random graphs
on the evolution of random graphson the evolution of random graphs
on the evolution of random graphshuwenbiao
 
Introduction to Marketing for Managers
Introduction to Marketing for ManagersIntroduction to Marketing for Managers
Introduction to Marketing for ManagersTony Ahn & Co.
 
Gilgamesh, El Inmortal - E2 056
Gilgamesh, El Inmortal - E2 056Gilgamesh, El Inmortal - E2 056
Gilgamesh, El Inmortal - E2 056Capitan667
 
unixtoolbox.pdf
unixtoolbox.pdfunixtoolbox.pdf
unixtoolbox.pdfsptlove
 
FirstGull - presentation
FirstGull - presentationFirstGull - presentation
FirstGull - presentationAndrey Veber
 
Гос. программа "Развитие информ. общества и гос. услуг в Ульяновской области ...
Гос. программа "Развитие информ. общества и гос. услуг в Ульяновской области ...Гос. программа "Развитие информ. общества и гос. услуг в Ульяновской области ...
Гос. программа "Развитие информ. общества и гос. услуг в Ульяновской области ...Денис Ефремов
 
представление прокурора края
представление прокурора краяпредставление прокурора края
представление прокурора краяurcis
 
Totalitarianism Summary Vocabulary
Totalitarianism Summary VocabularyTotalitarianism Summary Vocabulary
Totalitarianism Summary Vocabularycedarrobertson
 

Viewers also liked (20)

Object Oriented Programming for WordPress Plugin Development
Object Oriented Programming for WordPress Plugin DevelopmentObject Oriented Programming for WordPress Plugin Development
Object Oriented Programming for WordPress Plugin Development
 
Marriott 2.PDF
Marriott 2.PDFMarriott 2.PDF
Marriott 2.PDF
 
1 lh
1 lh1 lh
1 lh
 
Plan anticorrupcion la_pintada_version 1.0
Plan anticorrupcion la_pintada_version 1.0Plan anticorrupcion la_pintada_version 1.0
Plan anticorrupcion la_pintada_version 1.0
 
Doron yablekoviz_gastro_0111
Doron yablekoviz_gastro_0111Doron yablekoviz_gastro_0111
Doron yablekoviz_gastro_0111
 
1
11
1
 
Stanbic ibtc annual report 2009
Stanbic ibtc annual report 2009Stanbic ibtc annual report 2009
Stanbic ibtc annual report 2009
 
on the evolution of random graphs
on the evolution of random graphson the evolution of random graphs
on the evolution of random graphs
 
Introduction to Marketing for Managers
Introduction to Marketing for ManagersIntroduction to Marketing for Managers
Introduction to Marketing for Managers
 
Gilgamesh, El Inmortal - E2 056
Gilgamesh, El Inmortal - E2 056Gilgamesh, El Inmortal - E2 056
Gilgamesh, El Inmortal - E2 056
 
Nature10705
Nature10705Nature10705
Nature10705
 
unixtoolbox.pdf
unixtoolbox.pdfunixtoolbox.pdf
unixtoolbox.pdf
 
Engage for Success Essex
Engage for Success EssexEngage for Success Essex
Engage for Success Essex
 
Periodico
PeriodicoPeriodico
Periodico
 
FirstGull - presentation
FirstGull - presentationFirstGull - presentation
FirstGull - presentation
 
Гос. программа "Развитие информ. общества и гос. услуг в Ульяновской области ...
Гос. программа "Развитие информ. общества и гос. услуг в Ульяновской области ...Гос. программа "Развитие информ. общества и гос. услуг в Ульяновской области ...
Гос. программа "Развитие информ. общества и гос. услуг в Ульяновской области ...
 
Farm House
Farm HouseFarm House
Farm House
 
представление прокурора края
представление прокурора краяпредставление прокурора края
представление прокурора края
 
PLC_1
PLC_1PLC_1
PLC_1
 
Totalitarianism Summary Vocabulary
Totalitarianism Summary VocabularyTotalitarianism Summary Vocabulary
Totalitarianism Summary Vocabulary
 

Similar to Php object orientation and classes

Lecture 17 - PHP-Object-Orientation.pptx
Lecture 17 - PHP-Object-Orientation.pptxLecture 17 - PHP-Object-Orientation.pptx
Lecture 17 - PHP-Object-Orientation.pptxDavidLazar17
 
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
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Alena Holligan
 
Object oriented programming in php
Object oriented programming in phpObject oriented programming in php
Object oriented programming in phpAashiq Kuchey
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHPwahidullah mudaser
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Alena Holligan
 
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
 
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
 
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Alena Holligan
 
php_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdfphp_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdfakankshasorate1
 
php_final_sy_semIV_notes_vision (3).pdf
php_final_sy_semIV_notes_vision (3).pdfphp_final_sy_semIV_notes_vision (3).pdf
php_final_sy_semIV_notes_vision (3).pdfbhagyashri686896
 
php_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdfphp_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdfHarshuPawar4
 
php_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdfphp_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdfsannykhopade
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHPMichael Peacock
 
Framework prototype
Framework prototypeFramework prototype
Framework prototypeDevMix
 
Framework prototype
Framework prototypeFramework prototype
Framework prototypeDevMix
 

Similar to Php object orientation and classes (20)

Lecture 17 - PHP-Object-Orientation.pptx
Lecture 17 - PHP-Object-Orientation.pptxLecture 17 - PHP-Object-Orientation.pptx
Lecture 17 - PHP-Object-Orientation.pptx
 
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
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
 
Object oriented programming in php
Object oriented programming in phpObject oriented programming in php
Object oriented programming in php
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHP
 
Only oop
Only oopOnly oop
Only oop
 
Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18Demystifying Object-Oriented Programming #phpbnl18
Demystifying Object-Oriented Programming #phpbnl18
 
Demystifying oop
Demystifying oopDemystifying oop
Demystifying oop
 
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
 
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
 
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017
 
php_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdfphp_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdf
 
php_final_sy_semIV_notes_vision (3).pdf
php_final_sy_semIV_notes_vision (3).pdfphp_final_sy_semIV_notes_vision (3).pdf
php_final_sy_semIV_notes_vision (3).pdf
 
php_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdfphp_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdf
 
php_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdfphp_final_sy_semIV_notes_vision.pdf
php_final_sy_semIV_notes_vision.pdf
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
 

More from Kumar

Graphics devices
Graphics devicesGraphics devices
Graphics devicesKumar
 
Fill area algorithms
Fill area algorithmsFill area algorithms
Fill area algorithmsKumar
 
region-filling
region-fillingregion-filling
region-fillingKumar
 
Bresenham derivation
Bresenham derivationBresenham derivation
Bresenham derivationKumar
 
Bresenham circles and polygons derication
Bresenham circles and polygons dericationBresenham circles and polygons derication
Bresenham circles and polygons dericationKumar
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xsltKumar
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xmlKumar
 
Xml basics
Xml basicsXml basics
Xml basicsKumar
 
XML Schema
XML SchemaXML Schema
XML SchemaKumar
 
Publishing xml
Publishing xmlPublishing xml
Publishing xmlKumar
 
Applying xml
Applying xmlApplying xml
Applying xmlKumar
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XMLKumar
 
How to deploy a j2ee application
How to deploy a j2ee applicationHow to deploy a j2ee application
How to deploy a j2ee applicationKumar
 
JNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLJNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLKumar
 
EJB Fundmentals
EJB FundmentalsEJB Fundmentals
EJB FundmentalsKumar
 
JSP and struts programming
JSP and struts programmingJSP and struts programming
JSP and struts programmingKumar
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programmingKumar
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversKumar
 
Introduction to J2EE
Introduction to J2EEIntroduction to J2EE
Introduction to J2EEKumar
 

More from Kumar (20)

Graphics devices
Graphics devicesGraphics devices
Graphics devices
 
Fill area algorithms
Fill area algorithmsFill area algorithms
Fill area algorithms
 
region-filling
region-fillingregion-filling
region-filling
 
Bresenham derivation
Bresenham derivationBresenham derivation
Bresenham derivation
 
Bresenham circles and polygons derication
Bresenham circles and polygons dericationBresenham circles and polygons derication
Bresenham circles and polygons derication
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xslt
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xml
 
Xml basics
Xml basicsXml basics
Xml basics
 
XML Schema
XML SchemaXML Schema
XML Schema
 
Publishing xml
Publishing xmlPublishing xml
Publishing xml
 
DTD
DTDDTD
DTD
 
Applying xml
Applying xmlApplying xml
Applying xml
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
How to deploy a j2ee application
How to deploy a j2ee applicationHow to deploy a j2ee application
How to deploy a j2ee application
 
JNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLJNDI, JMS, JPA, XML
JNDI, JMS, JPA, XML
 
EJB Fundmentals
EJB FundmentalsEJB Fundmentals
EJB Fundmentals
 
JSP and struts programming
JSP and struts programmingJSP and struts programming
JSP and struts programming
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
 
Introduction to J2EE
Introduction to J2EEIntroduction to J2EE
Introduction to J2EE
 

Recently uploaded

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

Php object orientation and classes

  • 3. • Data membersData members • MethodsMethods
  • 4. Object OrientationObject Orientation  PHPisan Object-Oriented programming language  Fundamental feature of OO isthe classclass  PHPclassessupport − Encapsulation − Inheritance − Polymorphism
  • 5.
  • 6. What is aWhat is a ClassClass?? ClassesClasses  SophisticatedSophisticated ‘variable types’‘variable types’  Data variables (data membersdata members) and functions (methodsmethods) are wrapped up in a class. Collectively, data members and methods are referred to as classclass membersmembers. An instanceinstance of a classof a class is known as an objectobject. //defining a new class named Robot class RobotRobot {{ //place class members here... }}
  • 7.
  • 8. Instantiating a class usingInstantiating a class using newnew  Once a classhasbeen created, any numberany number of object instancesof that classcan be created.  $dogRobot = newnew Robot()Robot();  To invoke methods: − object->->method()  e.g. <?php .... $dogRobot = newnew Robot()Robot(); $dogRobot ->crawlWeb(); $dogRobot -> play(); echo $dogRobot ->talk(); ... ?>
  • 9. <?php class Person { private $strFirstname = “Napoleon"; private $strSurname = “Reyes"; function getFirstname() { return $this->strFirstname; } function getSurname() { return $this->strSurname; } } // outside the class definition $obj = newnew Person; // an object of type Person echo "<p>Firstname: " . $obj->getFirstname() . "</p>"; echo "<p>Surname: " . $obj->getSurname() . "</p>"; ?> Defining classesDefining classes Data members Methods Example16-1.php
  • 10.
  • 11. EncapsulationEncapsulation Data membersData members are normally set inaccessible from outside the class (as well as certain types of methodsmethods) protecting them from the rest of the script and other classes. This protection of class members is known as encapsulationencapsulation.  e.g. <?php .... $dogRobot = newnew Robot()Robot(); $dogRobot ->crawlWeb(); $dogRobot -> play(); echo $dogRobot ->talk(); ... ?>
  • 12. InheritanceInheritance New classesNew classes can be defined very similar to existing onesexisting ones. All we need to do is specify the differencesdifferences between the new class and the existing one. Data membersData members and methodsmethods which are notnot defined as being privateprivate to a class are automatically accessible by the new class. This is known as inheritanceinheritance and is an extremely powerful and useful programming tool.
  • 13. PolymorphismPolymorphism A concept where a number of related classesrelated classes all have a methodmethod, which shares the same name. class Fish { draw()...draw()... //draws a fish//draws a fish...... }} class Dog { draw()...draw()... //draws a dog//draws a dog...... }} class Bird { draw()...draw()... //draws a bird//draws a bird...... }} We can write a generic code that can operate on anycan operate on any of these classes, invoking the appropriate draw()draw() method based on certain conditions.
  • 14.
  • 15. Example:Example: Defining classesDefining classes class ShoppingCart { private $name; // Name of shoppershopper private $items; // Items in our shopping cartItems in our shopping cart public function ShoppingCartShoppingCart($inputname) { $this->name = $inputname; } // Add $num articles of $artnr to the cart public function addItemaddItem($artnr, $num) { $this->items[$artnr] += $num; } // Take $num articles of $artnr out of the cart public function removeItemremoveItem($artnr, $num) { if ($this->items[$artnr] > $num) { $this->items[$artnr] -= $num; return true; } elseif ($this->items[$artnr] == $num) { unset($this->items[$artnr]); return true; } else { return false; } } } Let’sexamine the syntax of defining a classnext...
  • 16.
  • 17. Data members and MethodsData members and Methods class Class1Class1 { private $strName$strName = “A”; private $intNumber$intNumber = 1; function getName()Name() { } function getNumber()getNumber(){ } }  We need to provide accessor functionsto allow usersof Class1 to accessthe privateprivate data members: function getName()getName(){ return $this->this->strNamestrName; } Isthispublicly accessible?
  • 18. $this$this object pointerobject pointer  Aswith so many languages, there isa special pointer that referencesan instance of a class: − $this$this function getName(){ return $this->strName; } function getName(){ return strName; }  
  • 19. Invoking methodsInvoking methods inside a classinside a class class Person{ ... function setFirstname($strSurname) { $this->strFirstname = $strSurname; } function setSurname($strSurname) { $this->strSurname = $strSurname; } private function display() { echo "<p>Firstname: " . $this->strFirstname . "</p>"; echo "<p>Surname: " . $this->strSurname . "</p>"; } function setDisplayFirstnameSurname($strFirstname, $strSurname) { $this->$this->setFirstname($strFirstname); $this->$this->setSurname($strSurname); $this->$this->display(); } } $this->$this->functionName(); Example16-4.php
  • 20.
  • 21. ClassesClasses class MyClassNameMyClassName{ ....methods ....data members }  Visibility of a method or data member: − PublicPublic − ProtectedProtected − PrivatePrivate − By defaultBy default, without the accessspecifiers, class membersclass members are defined publicpublic.
  • 22. PrivatePrivate Access SpecifierAccess Specifier class MyClassNameMyClassName{ privateprivate $strFirstName; }  privateprivate – limitsthe visibility of the methods and data members only to the classthat definesthem.
  • 23. Modifying data membersModifying data members  Outside the class, trying to execute the following: $clMyObj->intNumber++intNumber++;  will fail!...  We need a method to accessand change itsvalue: function setNumber($intNumber) { $this->intNumber = $intNumber; } intNumberintNumber is privateprivate Look at the position of the dollar sign ($) – no longer attached to the variable name
  • 24. PublicPublic Access SpecifierAccess Specifier class MyClassNameMyClassName{ publicpublic $strFirstName; publicpublic function getFirstName()getFirstName(){ } }  publicpublic – class memberscan be accessed both withinwithin and outsideand outside the class.
  • 25. ProtectedProtected Access SpecifierAccess Specifier Class MyClassNameMyClassName{ protectedprotected $strFirstName; protectedprotected function getFirstName()getFirstName(){ } }  InheritedInherited protectedprotected class membersclass members – accessible inside a derived classderived class  Visibility ofVisibility of protectedprotected class membersclass members outside the class definitionoutside the class definition – protected classmembersare inaccessible. //protected for public use, but accessible in a derived class
  • 26.
  • 28. <?php class MyClass { public $public = 'Public'; protected $protected = 'Protected'; //protected for public use, but accessible in a derived class private $private = 'Private'; function printHello()printHello() { echo $this->public; echo $this->protected; echo $this->private; } } // outside the class definition $obj = new MyClass(); echo $obj->public; // Works echo $obj->protected; // Fatal Error echo $obj->private; // Fatal Error $obj->printHello(); // Shows Public, Protected and Private //... Example:Example: Access SpecifiersAccess Specifiers     http://php.net/manual/en/language.oop5.visibility.php
  • 29. <?php //... class MyClass2 extendsextends MyClass { // We can redeclare the public and protected method, but not private // protected – ‘protected’ for public use, but accessible in a derived class protected $protected = 'Protected2'; function printHello() { echo $this->public; echo $this->protected; echo $this->private; } } // outside the class definition $obj2 = new MyClass2(); echo $obj2->public; // Works echo $obj2->private; // Undefined echo $obj2->protected; // Fatal Error $obj2->printHello(); // Shows Public, Protected2, Undefined ?> Example:Example: Access SpecifiersAccess Specifiers    http://php.net/manual/en/language.oop5.visibility.php a Derived class
  • 31. //OUTSIDE THE CLASS DEFINITION... $myclass = new MyClass; $myclass->MyPublic(); // Works $myclass->MyProtected(); // Fatal Error $myclass->MyPrivate(); // Fatal Error $myclass->Foo(); // Public, Protected and Private work //... <?php class MyClass { // Declare a public constructor public function __construct() { } // Declare a public method public function MyPublic() { } // Declare a protected method protected function MyProtected() { } // Declare a private method private function MyPrivate() { } // This is public function Foo() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); } }    http://php.net/manual/en/language.oop5.visibility.php Example:Example: Method DeclarationMethod Declaration
  • 32. class MyClass2 extendsextends MyClass { // This is public function Foo2() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); // Fatal Error } } $myclass2 = newnew MyClass2; $myclass2->MyPublic(); // Works $myclass2->Foo2(); // Public and Protected work, not Private Example:Example: Method DeclarationMethod Declaration    http://php.net/manual/en/language.oop5.visibility.php <?php class MyClass { // Declare a public constructor public function __construct() { } // Declare a public method public function MyPublic() { } // Declare a protected method protected function MyProtected() { } // Declare a private method private function MyPrivate() { } // This is public function Foo() { $this->MyPublic(); $this->MyProtected(); $this->MyPrivate(); } }
  • 33. $myFoo = new foo(); $myFoo->test(); // Bar::testPrivate // Foo::testPublic ?> Example:Example: Method DeclarationMethod Declaration   http://php.net/manual/en/language.oop5.visibility.php <?php class Bar { public function test() { $this->testPrivate(); $this->testPublic(); } public function testPublic() { echo "Bar::testPublicn"; } private function testPrivate() { echo "Bar::testPrivaten"; } } class Foo extends Bar { public function testPublic() { echo "Foo::testPublicn"; } private function testPrivate() { echo "Foo::testPrivaten"; } }
  • 34. string(5) "hello" Accessed the private method Accessing Private Members of theAccessing Private Members of the same object typesame object type  http://php.net/manual/en/language.oop5.visibility.php <?php class Test { private $foo; public function __construct($foo) { $this->foo = $foo; } private function bar() { echo 'Accessed the private method.'; } public function baz(Test $other) { // We can change the private property: $other->foo = 'hello'; var_dump($other->foo); // We can also call the private method: $other->bar(); } } $test = new Test('test'); $test->baz(new Test('other')); ?> Objectsof the same type will have accessto each others Private and protected memberseven though they are not the same instances.
  • 35.
  • 36. Creating objectsCreating objects •Instantiate classes using new keyword –$myCart= newnew ShoppingCart(“Charlie”); ConstructorsConstructors –In earlier versions of PHP (< PHP5.3.3PHP5.3.3) Same as the name of the class. This no longer holds!This no longer holds! – (PHP5 onlyPHP5 only) declared as •public function __construct(…) DestructorsDestructors –Declared as –public function __destruct()
  • 37. Latest in PHPLatest in PHP5.3.35.3.3 <?php namespace Foo; class Bar { public function Bar() { // treated as constructor in PHP 5.3.0-5.3.2 // treated as regular method in PHP 5.3.3 } } ?> 22 Sept. 2010
  • 38. ConstructorsConstructors  A constructorconstructor isa function that does initializationswhen the classisinstantiated function __construct(__construct($intNumber, $strName)){ $this->set_intNumber($intNumber); $this->set_strName($strName); $this->printInit();//use thismethod }
  • 39. ConstructorsConstructors  Default argumentsDefault arguments function __construct ($strName = “A”, $intNumber=0) { $this->set_intNumber($int_Number); $this->set_strName($str_Name); }  Instantiating a classwithout parameterswill make use of the default values
  • 40. Another Example:Another Example: ConstructorsConstructors <?php class vehiclevehicle { private $strDescription; function getDescription() { return $this->strDescription; } function setDescription($strDescription) { $this->strDescription = $strDescription; } function __construct ($strDescription) { $this->strDescription = $strDescription; } } ?> vehicle.php
  • 41. Another Example:Another Example: ConstructorsConstructors <?php require_once("vehicle.php"); $objBike = new vehicle("Bicycle"); echo "<p>Vehicle: " . $objBike->getDescription() . "</p>"; ?> example16-7.php
  • 42. DestructorsDestructors  Called when objectsare destroyed – free up memory  e.g.: function __destruct () { echo “freeing up memory, destroying thisobject... <br>”; } This sample code above simply informs us that the object is being destroyed already.
  • 43. Objects as variablesObjects as variables  Can be used in arrays  Can be passed to functions  Passed as referencePassed as reference all the time (PHP 55)  e.g.: function test1($objClass1){ $objClass1->set_intName(“B”); }  No need to use && in the formal parameterin the formal parameter definition.definition. It isalwayspassed by reference.
  • 44. Arrays and objectsArrays and objects <?php function __autoload($class_name) { require_once $class_name . '.php'; } $objSimon = new revisedperson("Simon", "Stobart"); $objLiz = new revisedperson("Liz", "Hall"); $objIan = new revisedperson("Ian", "Walker"); $objBilly = new revisedperson("Billy", "Lee"); $objHayley = new revisedperson("Hayley", "West"); $arrPeople$arrPeople = array(array($objSimon, $objLiz, $objIan, $objBilly, $objHayley)); foreach($arrPeople$arrPeople as $objThePerson){ echo($objThePerson->->display()display()); } ?> The function display()display() is common to all array elements (elements = objects in this example). example16-9.php
  • 45. Multiple Object InstancesMultiple Object Instances <?php $cart1 = new ShoppingCart(“Joe Bloggs”); $cart1->addItem("10", 1); $cart2 = new ShoppingCart(“Fred Smith”); $cart2->addItem("0815", 3); ?>
  • 46. Example:Example: PolymorphismPolymorphism <?php function __autoload($class_name) { require_once $class_name . '.php'; } $objRectangle = new rectangle(100,50, "rectangle.gif"); $objSquare = new square(100, "square.gif"); $objTriangle = new triangle(50,100, "triangle.gif"); $objEllipse = new ellipse(50,100, "ellipse.gif"); $arrShapes = array ($objRectangle,$objSquare,$objTriangle,$objEllipse); foreach ($arrShapes as $objShape){ $objShape->display(); $objShape->area(); } ?> The functions area() and display() are common to all array elements, but executes a different formula for each type of object. Example17-5.php
  • 47. • Recommended: Create one PHP source file per classdefinition. • Thisaidsclassreuse and script clarity.
  • 48. Remember these PHP Constructs?Remember these PHP Constructs? • require(….)require(….) − Includesfile specified, terminatesterminates on errors • include(…)include(…) − Includesfile specified, gives warningwarning on errors • require_once(….)require_once(….) − Includesfile specified only if it hasnot already been included, terminatesterminates on errors • include_once(….)include_once(….) − Includesfile specified only if it hasnot already been included, gives warningwarning on errors Example16-6.php  Really useful but would require you to write a long list of include() or require() statements at the beginning of each script, one for each class. In PHP5, this is no longer necessary. You may define an __autoload function!
  • 49. functionfunction __autoload()__autoload() • The function is invoked automatically each time a class is required but has not been defined. • We can insert this function into our script: Example16-7.php function __autoload__autoload($class_name) { require_oncerequire_once $class_name . '.php'; } Note: Class_name = File_name
  • 50. functionfunction __autoload()__autoload() Example16-7.php <?php function __autoload__autoload($class_name) { require_once $class_name . '.php'; } $objSimon = newnew person; $objSimon->setDisplayFirstnameSurname(“Napoleon", “Reyes"); $objBike = newnew vehicle("Bicycle"); echo "<p>Vehicle: " . $objBike->getDescription() . "</p>"; ?> Classdefinition comesfrom another file.
  • 51. ExceptionsExceptions Like all good OO languages, PHP5 supports the exception mechanism for trapping and handling “unexpected conditionsunexpected conditions” Note: not all exceptions are necessarily errors Exceptions not supported in PHP4
  • 52. classclass MyExceptionMyException extendsextends Exception {{ // Redefine the exception so message isn't optional public function __construct($message, $code = 0) { // some code // make sure everything is assigned properly parent::__construct($message, $code); } // custom string representation of object public function __toString() { return __CLASS__ .. ": $this->messagen"; } public function customFunction() { echo "A Custom function for this type of exceptionn"; } }} Extend the built-in PHP Exception class with your ownExtend the built-in PHP Exception class with your own exceptions (as in Java)exceptions (as in Java) ExceptionsExceptions <?php Throw new MyExceptionMyException("Message to display"); ?> To generate an exception
  • 53. Objects can...Objects can...  Invoke another  Be embedded within another object  Support for: − Inheritance − Scope resolution ( :::: operator) − Classabstraction (define a classthat doesnot instantiate, use “abstractabstract classclass classnameclassname” ) − Polymorphism (same function nameswith different data / behaviour) − '====‘ to check if two object have the same attributesand values − '======‘ to check if two objectsare the same instance of the same class
  • 54. Advanced OO in PHPAdvanced OO in PHP  PHP5 hasrich OO support (similar to the Java model) − Single inheritance (multiple inheritance not allowed) − Abstract classesand methods − Interfaces  PHPisa reflective programming language − Namesof functions/classesto be invoked do not have to be hard wired  See also documentation at www.php.netwww.php.net
  • 55. Reflection-Oriented ProgrammingReflection-Oriented Programming // without reflection// without reflection $Foo = new Foo(); $Foo->hello(); // with reflection// with reflection $f = new ReflectionClassReflectionClass("Foo"); $m = $f->getMethod("hello"); $m->invoke( $f->newInstance() ); Normally, instructions are executed and data is processed; however, in some languages, programs can also treat instructions asinstructions as datadata and therefore make reflective modifications. http://en.wikipedia.org/wiki/Reflection_(computer_science) Program execution could be modified at run-time. New in PHP, not properly documented yet! http://nz2.php.net/manual/en/reflectionclass.newinstance.php
  • 56. For a complete reference http://www.php.net