SlideShare a Scribd company logo
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.";
}
}
Ad

More Related Content

What's hot (20)

JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
WebStackAcademy
 
Creating native apps with WordPress
Creating native apps with WordPressCreating native apps with WordPress
Creating native apps with WordPress
Marko Heijnen
 
Javascript
JavascriptJavascript
Javascript
Manav Prasad
 
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
WebStackAcademy
 
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...
Doug Jones
 
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
JWORKS powered by Ordina
 
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
Vibrant Technologies & Computers
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
Zeeshan Ahmed
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript Literacy
David Jacobs
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
Bala Narayanan
 
Advanced Interfaces and Repositories in Laravel
Advanced Interfaces and Repositories in LaravelAdvanced Interfaces and Repositories in Laravel
Advanced Interfaces and Repositories in Laravel
Jonathan Behr
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
Jason Straughan
 
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
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
WebStackAcademy
 
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
olegmmiller
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOM
Jalpesh Vasa
 
Php variables (english)
Php variables (english)Php variables (english)
Php variables (english)
Mahmoud Masih Tehrani
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Mats Bryntse
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
WebStackAcademy
 
Creating native apps with WordPress
Creating native apps with WordPressCreating native apps with WordPress
Creating native apps with WordPress
Marko Heijnen
 
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
WebStackAcademy
 
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...
Doug Jones
 
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
JWORKS powered by Ordina
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript Literacy
David Jacobs
 
Advanced Interfaces and Repositories in Laravel
Advanced Interfaces and Repositories in LaravelAdvanced Interfaces and Repositories in Laravel
Advanced Interfaces and Repositories in Laravel
Jonathan Behr
 
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
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
WebStackAcademy
 
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
olegmmiller
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOM
Jalpesh Vasa
 

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
baabtra.com - No. 1 supplier of quality freshers
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
Muhamad Al Imran
 
lab4_php
lab4_phplab4_php
lab4_php
tutorialsruby
 
lab4_php
lab4_phplab4_php
lab4_php
tutorialsruby
 
Php
PhpPhp
Php
Rajkiran Mummadi
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
Hans Jones
 
Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
baabtra.com - No. 1 supplier of quality freshers
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
Jamers2
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
ShishirKantSingh1
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
chartjes
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
AbhishekSharma2958
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
BoneyGawande
 
lecture 15.pptx
lecture 15.pptxlecture 15.pptx
lecture 15.pptx
ITNet
 
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?
Nikita Popov
 
DIG1108C Lesson 6 - Fall 2014
DIG1108C Lesson 6 - Fall 2014DIG1108C Lesson 6 - Fall 2014
DIG1108C Lesson 6 - Fall 2014
David Wolfpaw
 
PHP - Introduction to PHP Functions
PHP -  Introduction to PHP FunctionsPHP -  Introduction to PHP Functions
PHP - Introduction to PHP Functions
Vibrant Technologies & Computers
 
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
rICh morrow
 
php fundamental
php fundamentalphp fundamental
php fundamental
zalatarunk
 
php
phpphp
php
Ramki Kv
 
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
 
Ad

More from Jalpesh Vasa (13)

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

Recently uploaded (20)

Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 

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."; } }