PHP With Oops
PHP With Oops
$obj->work();
?>
Inheritance
• Inheritance is one of the most important
aspects of OOP. It allows a class to inherit
members from another class.
• It helps in code reuse and code reduction.
• We declare a new class with additional
keyword extends.
• Note : PHP only supports multilevel
inheritance.
class empl extends person
Example {
<?php var $desg;
class person var $comp;
{ var $comp_cont;
var $name; }
var $add; $emp = new empl();
var $phone; echo $emp->name=“QWERTY"."</br>";
echo $emp->add=“XYZ"."</br>";
}
echo $emp->phone="789"."</br>";
echo $emp->desg=“DY.ER"."</br>";
echo $emp->comp=“ABCD"."</br>";
echo $emp->comp_cont="123"."</br>";
?>
Exception
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.
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
Try, throw and catch
To avoid the error from the example above, we need
to create the proper code to handle an exception.
Proper exception code should include:
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
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception in a "try" block
try {
checkNum(1);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below’;
}e
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>