SlideShare a Scribd company logo
1 of 42
Download to read offline
Object Oriented PHP
By: Jalpesh Vasa
Class unitcounter
{
var $units;
var $weightperunit;
function add($n=1)
{
$this->units = $this->units+$n;
}
function toatalweight()
{
return $this->units * $this->weightperunit;
}
function _ _construct($unitweight=1.0)
{
$this->weightperunit = $unitweight;
$this->units=0;
}
}
$brick = new unitcounter(1.2);
$brick->add(3)
$w1 = $brick->totalweight();
print “total weight of {$brick->units} bricks = $w1”;
Cloning Objects
• A variable assigned with an objects is actually
a reference to the object.
• Copying a object variable in PHP simply
creates a second reference to the same object.
• Example:
$a = new unitcounter();
$a->add(5);
$b=$a;
$b->add(5);
Echo “number of units={$a->units}”;
Echo “number of units={$b->units}”;
//prints number of units = 10
• The _ _clone() method is available, if you want
to create an independent copy of an object.
$a = new unitcounter();
$a->add(5);
$b=$a->_ _clone();
$b->add(5);
Echo “number of units={$a->units}”; //prints 5
Echo “number of units={$b->units}”; //prints 10
Inheritance
• One of most powerful concept of OOP
• Allows a new class to be defined by extending
the capabilities of an existing base class or
parent class.
<?php
Require “a1.php”;
Class casecounter extends unitcounter
{
var $unitpercase;
function addcase()
{
$this->add($this->unitpercase);
}
function casecount()
{
return ceil($this->units/$this->unitpercase);
}
function casecounter($casecapacity)
{
$this->unitpercase = $casecapacity;
}
}
?>
$order = new casecounter(12);
$order->add(7);
$order->addcase();
Print $order->units; // prints 17
Print $order->casecount(); //prints 2
Calling a parent class constructor
<?php
Require “a1.php”;
Class casecounter extends unitcounter
{
var $unitpercase;
function addcase()
{
$this->add($this->unitpercase);
}
function casecount()
{
return ceil($this->units/$this->unitpercase);
}
function casecounter($casecapacity, $unitweight)
{
parent::_ _construct($unitweight);
$this->unitpercase = $casecapacity;
}
}
?>
Function overriding
Class shape
{
function info()
{
return “shape”;
}
}
Class polygon extends shape
{
function info()
{
return “polygon”;
}
}
$a = new shape();
$b = new polygon();
Print $a->info(); //prints shape
Print $b->info(); //prints polygon
Function overriding
Class polygon extends shape
{
function info()
{
return parent::info().“.polygon”;
}
}
$b = new polygon();
Print $b->info(); //prints shape.polygon
Function overriding
Class triangle extends polygon
{
function info()
{
return parent::info().“.triangle”;
}
}
$t = new triangle();
Print $t->info(); //prints shape.polygon.triangle
Protected member variables and functions
• Member variables and functions can be defined
using protected keyword.
• Offers a compromise between being public and
private.
• It allows access to member variables and functions
defined in a class from within descendant classes,
but it prevents access from outside of the class
hierarchy.
• A child class can access a parent class’s protected
function, but parent class protected function can’t
be accessed from an unrelated class or from within a
script that uses the class.
Final functions
• Descendant classes can be prevented from
redefining member functions in base class by
declaring them as final
• Final keyword prevents accidental redefinition
in a descendant class.
Error Handling
• Error handling is the process of catching errors
raised by your program and then taking
appropriate action.
• The default error handling in PHP is very simple.
• An error message with filename, line number and
a message describing the error is sent to the
browser.
• We will show different error handling methods:
– Simple "die()" statements
– Custom errors and error triggers
– Error reporting
Using the die() function
• While writing your PHP program you should check all
possible error condition before going ahead and take
appropriate action when required.
<?php
if(!file_exists("/tmp/test.txt"))
{
die("File not found");
}
else {
$file=fopen("/tmp/test.txt","r");
print "Opend file sucessfully"; }
// Test of the code here. ?>
Using the die() function
• Now if the file does not exist you get an error like
this:
File not found
• The code above is more efficient than the earlier
code, because it uses a simple error handling
mechanism to stop the script after the error.
Defining Custom Error Handling Function
• You can write your own function to handling any
error. PHP provides you a framework to define
error handling function.
• This function must be able to handle a minimum
of two parameters (error level and error
message) but can accept up to five parameters
(optionally: file, line-number, and the error
context):
• error_function(error_level,error_message,
error_file,error_line,error_context);
Defining Custom Error Handling Function
Parameter Description
error_level Required. Specifies the error report level for the user-
defined error. Must be a value number. See table
below for possible error report levels
error_message Required. Specifies the error message for the user-
defined error
error_file Optional. Specifies the filename in which the error
occurred
error_line Optional. Specifies the line number in which the
error occurred
error_context Optional. Specifies an array containing every variable,
and their values, in use when the error occurred
Error Report levels
Value Constant Description
2 E_WARNING Non-fatal run-time errors. Execution of the script is not
halted
8 E_NOTICE Run-time notices. The script found something that
might be an error, but could also happen when running
a script normally
256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by
the programmer using the PHP function trigger_error()
512 E_USER_WARNING Non-fatal user-generated warning. This is like an
E_WARNING set by the programmer using the PHP
function trigger_error()
1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by
the programmer using the PHP function trigger_error()
4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be
caught by a user defined handle (see also
set_error_handler())
8191 E_ALL All errors and warnings (E_STRICT became a part of
E_ALL in PHP 5.4)
Defining Custom Error Handling Function
• Now lets create a function to handle errors:
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}
OR
function handleError($errno, $errstr,$error_file,$error_line)
{
echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";
echo "<br />";
echo "Terminating PHP Script";
die();
}
Set Error Handler
• The default error handler for PHP is the built in error handler. We are going to
make the function above the default error handler for the duration of the
script.
<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr";
}
//set error handler
set_error_handler("customError");
//trigger error
echo($test);
?>
Error: [8] Undefined variable: test
PHP Exception Handling
• Exception handling is used to change the
normal flow of the code execution if a
specified error (exceptional) condition occurs.
This condition is called an exception.
• Exceptions give us much better handling of
errors an allow us to customize the behavior
of our scripts when an error (Exception) is
encountered.
• Exceptions are important and provides a
better control over error handling.
PHP Exception Handling
• This is what normally happens when an
exception is triggered:
• The current code state is saved
• The code execution will switch to a predefined (custom)
exception handler function
• Depending on the situation, the handler may then
resume the execution from the saved code state,
terminate the script execution or continue the script
from a different location in the code
PHP Exception Handling
• Exceptions are actually objects and you have the option to 'catch'
them and execute certain code. This is done by using 'try-catch'
blocks:
try {
// some code goes here
// which might throw an exception
}
catch (Exception $e) {
// the code here only gets executed
// if an exception happened in the try block above
}
PHP Exception Handling
• Lets explain three new keyword related to
exceptions.
• Try - A function using an exception should be in a
"try" block. If the exception does not trigger, the
code will continue as normal. However if the
exception triggers, an exception is "thrown".
• Throw - This is how you trigger an exception.
Each "throw" must have at least one "catch".
• Catch - - A "catch" block retrieves an exception
and creates an object containing the exception
information.
PHP Exception Handling
• Let's say you want to calculate the area of a
circle, by the given radius. This function will do
that:
function circle_area($radius)
{
return pi() * $radius * $radius;
}
PHP Exception Handling
• It is very simple, however it does not check if the radius is
a valid number. Now we are going to do that, and throw
an exception if the radius is a negative number:
function circle_area($radius) {
// radius can't be negative
if ($radius < 0) {
throw new Exception('Invalid Radius: ' . $radius);
}
else
{
return pi() * $radius * $radius;
}
}
PHP Exception Handling
• Let's see what happens when we call it with a
negative number:
$radius = -2;
echo "Circle Radius: $radius => Circle Area: ".
circle_area($radius) . "n";
echo "Another line";
PHP Exception Handling
• The script crashes with the following message:
<br />
<b>Fatal error</b>: Uncaught exception 'Exception'
with message 'Invalid Radius: -2' in
C:wampwwwtesttest.php:19
Stack trace:
#0 C:wampwwwtesttest.php(7): circle_area(-2)
#1 {main}
thrown in <b>C:wampwwwtesttest.php</b> on
line <b>19</b><br />
PHP Exception Handling
$radius_array = array(2,-2,5,-3);
foreach ($radius_array as $radius) {
try {
echo "Circle Radius: $radius => Circle Area: ".
circle_area($radius) . "n";
} catch (Exception $e) {
echo 'Caught Exception: ', $e->getMessage(), "n";
}
}
PHP Exception Handling
Now we get this output:
Circle Radius: 2 => Circle Area: 12.566370614359
Caught Exception: Invalid Radius: -2
Circle Radius: 5 => Circle Area: 78.539816339745
Caught Exception: Invalid Radius: -3
There are no more errors, and the script continues
to run. That is how you catch exceptions.
PHP Exception Handling
• When an exception is thrown from a function or
a class method, it goes to whoever called that
function or method. And it keeps on doing this
until it reaches the top of the stack OR is caught.
If it does reach the top of the stack and is never
called, you will get a fatal error.
PHP Exception Handling
function bar() {
throw new Exception('Message from bar().');
}
function foo() {
bar();
}
try {
foo();
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "n“;
PHP Exception Handling
• In the above example $e->getMessage function
is used to get error message. There are following
functions which can be used
from Exception class.
• getMessage()- message of exception
• getCode() - code of exception
• getFile() - source filename
• getLine() - source line
• getTrace() - n array of the backtrace()
• getTraceAsString() - formated string of trace
File upload in PHP
• How to upload file on server?
• How to limit size of file?
• How to check /limit file type?
• Where to store your file?
File upload in PHP
• First, ensure that PHP is configured to allow file
uploads.
• In your "php.ini" file, search for
the file_uploads directive, and set it to On:
• file_uploads = On
File upload in PHP(html file)
• <!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart
/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
File upload in PHP(html file)
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
File upload in PHP(html file)
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
File upload in PHP(html file)
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" &&
$imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
File upload in PHP(html file)
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
$target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). "
has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}

More Related Content

What's hot

A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented Php
Michael Girouard
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Muhamad Al Imran
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Muhamad Al Imran
 

What's hot (20)

JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
Creating native apps with WordPress
Creating native apps with WordPressCreating native apps with WordPress
Creating native apps with WordPress
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
PHP - Introduction to PHP Date and Time Functions
PHP -  Introduction to  PHP Date and Time FunctionsPHP -  Introduction to  PHP Date and Time Functions
PHP - Introduction to PHP Date and Time Functions
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript Literacy
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Advanced Interfaces and Repositories in Laravel
Advanced Interfaces and Repositories in LaravelAdvanced Interfaces and Repositories in Laravel
Advanced Interfaces and Repositories in Laravel
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented Php
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
 
Create a web-app with Cgi Appplication
Create a web-app with Cgi AppplicationCreate a web-app with Cgi Appplication
Create a web-app with Cgi Appplication
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOM
 
Php variables (english)
Php variables (english)Php variables (english)
Php variables (english)
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 

Similar to Object Oriented PHP - PART-2

Php introduction with history of php
Php introduction with history of phpPhp introduction with history of php
Php introduction with history of php
pooja bhandari
 

Similar to Object Oriented PHP - PART-2 (20)

Introduction to php exception and error management
Introduction to php  exception and error managementIntroduction to php  exception and error management
Introduction to php exception and error management
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
lab4_php
lab4_phplab4_php
lab4_php
 
lab4_php
lab4_phplab4_php
lab4_php
 
Php
PhpPhp
Php
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
lecture 15.pptx
lecture 15.pptxlecture 15.pptx
lecture 15.pptx
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
DIG1108C Lesson 6 - Fall 2014
DIG1108C Lesson 6 - Fall 2014DIG1108C Lesson 6 - Fall 2014
DIG1108C Lesson 6 - Fall 2014
 
PHP - Introduction to PHP Functions
PHP -  Introduction to PHP FunctionsPHP -  Introduction to PHP Functions
PHP - Introduction to PHP Functions
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
 
php fundamental
php fundamentalphp fundamental
php fundamental
 
Php introduction with history of php
Php introduction with history of phpPhp introduction with history of php
Php introduction with history of php
 
php
phpphp
php
 

More from Jalpesh Vasa

More from Jalpesh Vasa (13)

5. HTML5
5. HTML55. HTML5
5. HTML5
 
4.4 PHP Session
4.4 PHP Session4.4 PHP Session
4.4 PHP Session
 
4.3 MySQL + PHP
4.3 MySQL + PHP4.3 MySQL + PHP
4.3 MySQL + PHP
 
4.1 PHP Arrays
4.1 PHP Arrays4.1 PHP Arrays
4.1 PHP Arrays
 
4 Basic PHP
4 Basic PHP4 Basic PHP
4 Basic PHP
 
3.2.1 javascript regex example
3.2.1 javascript regex example3.2.1 javascript regex example
3.2.1 javascript regex example
 
3.2 javascript regex
3.2 javascript regex3.2 javascript regex
3.2 javascript regex
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
 
2 introduction css
2 introduction css2 introduction css
2 introduction css
 
1 web technologies
1 web technologies1 web technologies
1 web technologies
 
Remote Method Invocation in JAVA
Remote Method Invocation in JAVARemote Method Invocation in JAVA
Remote Method Invocation in JAVA
 
Kotlin for android development
Kotlin for android developmentKotlin for android development
Kotlin for android development
 
Security in php
Security in phpSecurity in php
Security in php
 

Recently uploaded

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Recently uploaded (20)

Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 

Object Oriented PHP - PART-2

  • 1. Object Oriented PHP By: Jalpesh Vasa
  • 2. Class unitcounter { var $units; var $weightperunit; function add($n=1) { $this->units = $this->units+$n; } function toatalweight() { return $this->units * $this->weightperunit; } function _ _construct($unitweight=1.0) { $this->weightperunit = $unitweight; $this->units=0; } } $brick = new unitcounter(1.2); $brick->add(3) $w1 = $brick->totalweight(); print “total weight of {$brick->units} bricks = $w1”;
  • 3. Cloning Objects • A variable assigned with an objects is actually a reference to the object. • Copying a object variable in PHP simply creates a second reference to the same object. • Example:
  • 4. $a = new unitcounter(); $a->add(5); $b=$a; $b->add(5); Echo “number of units={$a->units}”; Echo “number of units={$b->units}”; //prints number of units = 10
  • 5. • The _ _clone() method is available, if you want to create an independent copy of an object. $a = new unitcounter(); $a->add(5); $b=$a->_ _clone(); $b->add(5); Echo “number of units={$a->units}”; //prints 5 Echo “number of units={$b->units}”; //prints 10
  • 6. Inheritance • One of most powerful concept of OOP • Allows a new class to be defined by extending the capabilities of an existing base class or parent class.
  • 7. <?php Require “a1.php”; Class casecounter extends unitcounter { var $unitpercase; function addcase() { $this->add($this->unitpercase); } function casecount() { return ceil($this->units/$this->unitpercase); } function casecounter($casecapacity) { $this->unitpercase = $casecapacity; } } ?>
  • 8. $order = new casecounter(12); $order->add(7); $order->addcase(); Print $order->units; // prints 17 Print $order->casecount(); //prints 2
  • 9. Calling a parent class constructor <?php Require “a1.php”; Class casecounter extends unitcounter { var $unitpercase; function addcase() { $this->add($this->unitpercase); } function casecount() { return ceil($this->units/$this->unitpercase); } function casecounter($casecapacity, $unitweight) { parent::_ _construct($unitweight); $this->unitpercase = $casecapacity; } } ?>
  • 10. Function overriding Class shape { function info() { return “shape”; } } Class polygon extends shape { function info() { return “polygon”; } } $a = new shape(); $b = new polygon(); Print $a->info(); //prints shape Print $b->info(); //prints polygon
  • 11. Function overriding Class polygon extends shape { function info() { return parent::info().“.polygon”; } } $b = new polygon(); Print $b->info(); //prints shape.polygon
  • 12. Function overriding Class triangle extends polygon { function info() { return parent::info().“.triangle”; } } $t = new triangle(); Print $t->info(); //prints shape.polygon.triangle
  • 13. Protected member variables and functions • Member variables and functions can be defined using protected keyword. • Offers a compromise between being public and private. • It allows access to member variables and functions defined in a class from within descendant classes, but it prevents access from outside of the class hierarchy. • A child class can access a parent class’s protected function, but parent class protected function can’t be accessed from an unrelated class or from within a script that uses the class.
  • 14. Final functions • Descendant classes can be prevented from redefining member functions in base class by declaring them as final • Final keyword prevents accidental redefinition in a descendant class.
  • 15. Error Handling • Error handling is the process of catching errors raised by your program and then taking appropriate action. • The default error handling in PHP is very simple. • An error message with filename, line number and a message describing the error is sent to the browser. • We will show different error handling methods: – Simple "die()" statements – Custom errors and error triggers – Error reporting
  • 16. Using the die() function • While writing your PHP program you should check all possible error condition before going ahead and take appropriate action when required. <?php if(!file_exists("/tmp/test.txt")) { die("File not found"); } else { $file=fopen("/tmp/test.txt","r"); print "Opend file sucessfully"; } // Test of the code here. ?>
  • 17. Using the die() function • Now if the file does not exist you get an error like this: File not found • The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error.
  • 18. Defining Custom Error Handling Function • You can write your own function to handling any error. PHP provides you a framework to define error handling function. • This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context): • error_function(error_level,error_message, error_file,error_line,error_context);
  • 19. Defining Custom Error Handling Function Parameter Description error_level Required. Specifies the error report level for the user- defined error. Must be a value number. See table below for possible error report levels error_message Required. Specifies the error message for the user- defined error error_file Optional. Specifies the filename in which the error occurred error_line Optional. Specifies the line number in which the error occurred error_context Optional. Specifies an array containing every variable, and their values, in use when the error occurred
  • 20. Error Report levels Value Constant Description 2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted 8 E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script normally 256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error() 512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error() 1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error() 4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler()) 8191 E_ALL All errors and warnings (E_STRICT became a part of E_ALL in PHP 5.4)
  • 21. Defining Custom Error Handling Function • Now lets create a function to handle errors: function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br>"; echo "Ending Script"; die(); } OR function handleError($errno, $errstr,$error_file,$error_line) { echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line"; echo "<br />"; echo "Terminating PHP Script"; die(); }
  • 22. Set Error Handler • The default error handler for PHP is the built in error handler. We are going to make the function above the default error handler for the duration of the script. <?php //error handler function function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr"; } //set error handler set_error_handler("customError"); //trigger error echo($test); ?> Error: [8] Undefined variable: test
  • 23. PHP Exception Handling • Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception. • Exceptions give us much better handling of errors an allow us to customize the behavior of our scripts when an error (Exception) is encountered. • Exceptions are important and provides a better control over error handling.
  • 24. PHP Exception Handling • This is what normally happens when an exception is triggered: • The current code state is saved • The code execution will switch to a predefined (custom) exception handler function • Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code
  • 25. PHP Exception Handling • Exceptions are actually objects and you have the option to 'catch' them and execute certain code. This is done by using 'try-catch' blocks: try { // some code goes here // which might throw an exception } catch (Exception $e) { // the code here only gets executed // if an exception happened in the try block above }
  • 26. PHP Exception Handling • Lets explain three new keyword related to exceptions. • Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown". • Throw - This is how you trigger an exception. Each "throw" must have at least one "catch". • Catch - - A "catch" block retrieves an exception and creates an object containing the exception information.
  • 27. PHP Exception Handling • Let's say you want to calculate the area of a circle, by the given radius. This function will do that: function circle_area($radius) { return pi() * $radius * $radius; }
  • 28. PHP Exception Handling • It is very simple, however it does not check if the radius is a valid number. Now we are going to do that, and throw an exception if the radius is a negative number: function circle_area($radius) { // radius can't be negative if ($radius < 0) { throw new Exception('Invalid Radius: ' . $radius); } else { return pi() * $radius * $radius; } }
  • 29. PHP Exception Handling • Let's see what happens when we call it with a negative number: $radius = -2; echo "Circle Radius: $radius => Circle Area: ". circle_area($radius) . "n"; echo "Another line";
  • 30. PHP Exception Handling • The script crashes with the following message: <br /> <b>Fatal error</b>: Uncaught exception 'Exception' with message 'Invalid Radius: -2' in C:wampwwwtesttest.php:19 Stack trace: #0 C:wampwwwtesttest.php(7): circle_area(-2) #1 {main} thrown in <b>C:wampwwwtesttest.php</b> on line <b>19</b><br />
  • 31. PHP Exception Handling $radius_array = array(2,-2,5,-3); foreach ($radius_array as $radius) { try { echo "Circle Radius: $radius => Circle Area: ". circle_area($radius) . "n"; } catch (Exception $e) { echo 'Caught Exception: ', $e->getMessage(), "n"; } }
  • 32. PHP Exception Handling Now we get this output: Circle Radius: 2 => Circle Area: 12.566370614359 Caught Exception: Invalid Radius: -2 Circle Radius: 5 => Circle Area: 78.539816339745 Caught Exception: Invalid Radius: -3 There are no more errors, and the script continues to run. That is how you catch exceptions.
  • 33. PHP Exception Handling • When an exception is thrown from a function or a class method, it goes to whoever called that function or method. And it keeps on doing this until it reaches the top of the stack OR is caught. If it does reach the top of the stack and is never called, you will get a fatal error.
  • 34. PHP Exception Handling function bar() { throw new Exception('Message from bar().'); } function foo() { bar(); } try { foo(); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "n“;
  • 35. PHP Exception Handling • In the above example $e->getMessage function is used to get error message. There are following functions which can be used from Exception class. • getMessage()- message of exception • getCode() - code of exception • getFile() - source filename • getLine() - source line • getTrace() - n array of the backtrace() • getTraceAsString() - formated string of trace
  • 36. File upload in PHP • How to upload file on server? • How to limit size of file? • How to check /limit file type? • Where to store your file?
  • 37. File upload in PHP • First, ensure that PHP is configured to allow file uploads. • In your "php.ini" file, search for the file_uploads directive, and set it to On: • file_uploads = On
  • 38. File upload in PHP(html file) • <!DOCTYPE html> <html> <body> <form action="upload.php" method="post" enctype="multipart /form-data"> Select image to upload: <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload Image" name="submit"> </form> </body> </html>
  • 39. File upload in PHP(html file) <?php $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } ?>
  • 40. File upload in PHP(html file) // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; }
  • 41. File upload in PHP(html file) // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; }
  • 42. File upload in PHP(html file) // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } }