This document discusses object oriented PHP concepts including classes, inheritance, overriding functions, error handling, and file uploads. It provides examples of creating a class with methods, instantiating objects, extending classes, overriding parent methods, and defining custom error handling functions. It also demonstrates how to upload files in PHP by handling the file on the server, checking for errors, and moving the file to a target directory.
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 />
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
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.";
}
}