Uploaded by Pratham p salvi

Unit 3-clg

advertisement
UNIT 3
Object oriented programming using PHP and
exception handling
BUILT IN FUNCTION
String function
• Finding Length of a String
• The strlen() function returns the length of any string. It's most
widely used in input fields where the user can only type a certain
number of characters.
• Syntax:
• Strlen(String);
<?php
echo strlen(‘Here is the string functions in php');//will return the
length of given string
?>
• Reversing a String
• This is one of the basic string functions in php Strrev() is a function
that reverses a string. This function can be used to get the reverse
version of any string.
<?php
echo strrev(‘Here is the string functions in php');//return the number
of words in an String
?>
• Searching Text in String
• Strpos() allows you to check for specific text within a string. It works
by simply matching a string's basic text. If a match is found, the
location is returned. It will return "False" if the item is not found at
all. Strpos() is widely used to validate input fields such as email
addresses.
• Syntax:
• Strpos(String,text);
<?php
echo strpos('Welcome to string functions in php','string');
?>
strrpos() function
• The strrpos() is an in-built function of PHP which is used
to find the position of the last occurrence of a substring
inside another string. It is a case-sensitive function of
PHP, which means it treats uppercase and lowercase
characters differently.
<?php
echo strrpos("I love php, I love php too!","php");
?>
chr() Function
• The PHP chr() function is used to generate a single byte
string from a number. In another words we can say that
it returns a character from specified ASCII value.
Syntax:
string chr ( int $bytevalue );
<?php
$char =52;
echo "Your character is :".$char;
echo "<br>"."By using 'chr()' function your value is: ".chr($char);
// decimal Value
?>
string ord() Function
• PHP string ord() is predefined function. It is used to
convert first byte of string to a value between 0 and 255.
It returns ASCII value.
• int ord ( string $string );
<?php
echo "Your Value is: A"."<br>";
echo "By using 'ord()' Function:".ord("A")."<br>";
?>
strcmp() Function
• The strcmp() function compares two strings.
• Syntax
• strcmp(string1,string2)
• <?php
• echo strcmp("Hello","Hello");
• echo "<br>";
• echo strcmp("Hello","hELLo");
• ?>
strcasecmp() Function
• The strcasecmp() function compares two strings.
• The strcasecmp() function is binary-safe and caseinsensitive.
Return
Value:
•This function returns:0 - if the two strings are equal
•<0 - if string1 is less than string2
•>0 - if string1 is greater than string2
• <?php
echo strcasecmp("Hello world!","HELLO WORLD!"); //
The two strings are equal
echo strcasecmp("Hello world!","HELLO"); // String1
is greater than string2
echo strcasecmp("Hello world!","HELLO WORLD!
HELLO!"); // String1 is less than string2
?>
strstr() Function
• The strstr() function searches for the first occurrence of
a string inside another string.
• Syntax
• strstr(string,search,before_search)
//Returns remaining string after search found
Input: $string1 = "Hello! Good Morning everyone",
$search1 = "Good";
Output: Morning everyone
substr() Function
• The substr() function returns a part of a string.
<?php
echo substr("Hello
echo substr("Hello
echo substr("Hello
echo substr("Hello
?>
world",10)."<br>";
world",1)."<br>";
world",3)."<br>";
world",7)."<br>";
strtolower() Function
• The strtolower() function converts a string to
lowercase.
• Syntax
• strtolower(string)
• <?php
echo strtolower("Hello WORLD.");
?>
strtoupper() Function
• The strtoupper() function converts a string to
uppercase.
• <?php
echo strtoupper("Hello WORLD!");
?>
ltrim() Function
• Remove characters from the left side of a string:
• The ltrim() function removes whitespace or other
predefined characters from the left side of a string.
• Syntax
• ltrim(string,charlist)
<?php
$str = "\n\n\nHello World!";
echo "Without ltrim: " . $str;
echo "<br>";
echo "With ltrim: " . ltrim($str);
?>
rtrim() Function
• The rtrim() function removes whitespace or other
predefined characters from the right side of a string.
• Specifies which characters to remove from the string. If
omitted, all of the following characters are
removed:"\0" - NULL
• "\t" - tab
• "\n" - new line
• "\x0B" - vertical tab
• "\r" - carriage return
• " " - ordinary white space
• <?php
$str = "Hello World!\n\n\n";
echo "Without rtrim: " . $str;
echo "<br>";
echo "With rtrim: " . rtrim($str);
?>
print() Function
The print() function outputs one or more strings.
<?php
$str = "Hello world!";
print $str;
?>
MATH FUNCTION
abs() function
• The abs() function returns absolute value of given number.
It returns an integer value but if you pass floating point
value, it returns a float value.
• Syntax
number abs ( mixed $number ) ;
<?php
echo(abs(6.7) . "<br>");
echo(abs(-6.7) . "<br>");
echo(abs(-3) . "<br>");
echo(abs(3));
?>
ceil() function
• The ceil() function rounds fractions up.
Syntax
float ceil ( float $value )
• Example
<?php
echo (ceil(3.3)."<br/>");// 4
echo (ceil(7.333)."<br/>");// 8
echo (ceil(-4.8)."<br/>");// -4
?>
floor() function
• The floor() function rounds fractions down.
Syntax
float floor ( float $value )
Example:
<?php
echo (floor(3.3)."<br/>");// 3
echo (floor(7.333)."<br/>");// 7
echo (floor(-4.8)."<br/>");// -5
?>
sqrt() function
The sqrt() function returns square root of given argument.
Syntax
float sqrt ( float $arg )
Example:
<?php
echo (sqrt(16)."<br/>");// 4
echo (sqrt(25)."<br/>");// 5
echo (sqrt(7)."<br/>");// 2.6457513110646
?>
round() Function
• The round() function rounds a floating-point number.
• Syntax
• round(number,precision,mode);
<?php
echo(round(0.60) . "<br>");
echo(round(0.50) . "<br>");
echo(round(0.49) . "<br>");
echo(round(-4.40) . "<br>");
echo(round(-4.60));
?>
fmod() Function
• PHP fmod() function is mathematical function, which is used to
return the floating point remainder of the division of the
argument.
Syntax:
float fmod ( float $x , float $y );
• Example
<?php
$x = 7;
$y = 2;
echo "Your Given Nos is : $x=7, $y=2"
$result ="By using 'fmod()' Function your value is:".fmod($x,$y);
echo $result;
// $result equals 1, because 2 * 3 + 1 = 7
?>
Max() Function
• The max() function is used to find the highest value.
• Syntax:
max(array_values);
• OR
• max(value1,value2,value3,value4...);
Example
<?php
$num=max(4,14,3,5,14.2);
echo "Your number is =max(4,14,3,5,14.2)".'<br>';
echo "By using max function Your number is : ".$num;
?>
Min() function
• PHP min() function is used to find the lowest value.
• Syntax:
min(array_values);
or
min(value1,value2,value3...);
• Example 1
<?php
$num=min(4,14,3,5,14.2);
echo "Your number is =min(4,14,3,5,14.2)".'<br>';
echo "By using min() function Your number is : ".$num;
?>
• Example 2
<?php
$ar=array(14,-18,4,8,15.5);
echo "Your number is =min(14,-18,4,8,15.5)".'<br>';
echo "By using min() function Your number is : ".min($ar);
?>
pow() function
• The pow() is a PHP mathematic function. It raises the
first number to the power of the second number.
• Syntax:
number pow ( number $base , number $exp )
<?php
$num=pow(3, 2);
echo "Your number is = pow (3, 2)".'<br>';
echo "By using sqrt function Your number is : ".$num;
?>
Rand() function
• The rand() function is used to generate random integer.
<?php
echo "To get random number b/w (rand(10,100)): ".(rand(10,100))
;
echo "<br>"."<br>"."Note: Refresh page to get new random numb
er";
?>
ARRAY FUNCTION
count() function
• PHP count() function counts all elements in an array.
• Example
<?php
$season=array("summer","winter","spring","autumn");
echo count($season);
?>
list() Function
• The list() function is used to assign values to a list of
variables in one operation.
<?php
$my_array = array("Dog","Cat","Horse");
list($a, $b, $c) = $my_array;
echo "I have several animals, a $a, a $b and a $c.";
?>
in_array() Function
• The in_array() function searches an array for a specific
value.
• Syntax
• in_array(search, array, type)
<?php
$fruit = array(“Banana", “Apple", “Guava”);
if (in_array(“Apple", $fruit))
{
echo "Match found";
}
else
{
echo "Match not found";
}
?>
current() Function
• The current() function returns the value of the current
element in an array.
• end() - moves the internal pointer to, and outputs, the
last element in the array
• next() - moves the internal pointer to, and outputs, the
next element in the array
• prev() - moves the internal pointer to, and outputs, the
previous element in the array
• <?php
• $arr = array('Sham', 'Mac', 'Jhon', 'Adwin');
• // Here current element is Sham.
• echo current($arr)."\n";
• // increment internal pointer to point
• // to next element i.e, Mac
• echo next($arr)."\n";
• // printing the current element as
• // for now current element is Mac.
• echo current($arr)."\n";
• // increment internal pointer to point
• // to next element i.e, Jhon.
• echo next($arr)."\n";
• // increment internal pointer to point
• // to next element i.e, Adwin.
• echo next($arr)."\n";
• // printing the current element as for
• // now current element is Adwin.
• echo current($arr)."\n";
• ?>
each() Function
• The each() function returns the current element key
and value, and moves the internal pointer forward.
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
print_r (each($people));
?>
sort() Function
• The sort() function sorts an indexed array in ascending
order.
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>
rsort() Function
• The rsort() function sorts an indexed array in
descending order.
• <?php
$cars=array("Volvo","BMW","Toyota");
rsort($cars);
?>
asort() Function
• The asort() function sorts an associative array in ascending
order, according to the value.
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
asort($age);
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
array_merge() Function
• The array_merge() function merges one or more arrays
into one array.
• If two or more array elements have the same key, the
last one overrides the others.
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
<?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));
?>
array_reverse() Function
• The array_reverse() function returns an array in the
reverse order.
<?php
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
print_r(array_reverse($a));
?>
User defined functions
• PHP has a large number of built-in functions such as
mathematical, string, date, array functions etc. It is also possible
to define a function as per specific requirement. Such function is
called user defined function.
• A function is a reusable block of statements that performs a
specific task. This block is defined with function keyword and is
given a name that starts with an alphabet or underscore. This
function may be called from anywhere within the program any
number of times.
Example
function with arguments
• function is defined with two formal arguments
<?php
function add($arg1,
$arg2){
echo $arg1+$arg2 . "";
}
add(10,20);
add("Hello", "World");
?>
function return
• User defined function in following example processes the
provided arguments and retuns a value to calling environment.
Define Class in PHP
• PHP classes are almost like functions but with a major different
that classes contain both variables and function, in a single
format called object or can be said Class is made from a
collection of objects.
class cars {
// Properties
var $name;
var $color;
Syntax:
<?php
class myFirstClass {
var $ var _ a ;
var $ var _ b = " constant string " ;
function classFunction ( $ parameter 1 , $ parameter 2 ) {
[...............]
}
[...............]
}
?>
Define Objects
objects of a class are created using the new keyword.
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
The __construct Function
A constructor allows you to initialize an object's properties upon creation of the object.
If you create a __construct() function, PHP will automatically call this function
when you create an object from a class.
the construct function starts with two underscores (__)!
<?php
class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit("Apple");
echo $apple->get_name();
The __destruct Function
A destructor is called when the object is destructed or the script is stopped or exited.
If you create a __destruct() function,
PHP will automatically call this function at the end of the script.
<?php
class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}
$apple = new Fruit("Apple");
?>
The $this Keyword
• The $this keyword refers to the current object, and is
only available inside methods.
• 1. Inside the class (by adding a set_name() method
and use $this):
• class Fruit {
public $name;
function set_name($name) {
$this->name = $name;
}
}
$apple = new Fruit();
$apple->set_name("Apple");
2. Outside the class (by directly changing the property
value):
• <?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";
echo $apple->name;
?>
Access Modifiers
Properties and methods can have access modifiers which control where they can be accessed.
There are three access modifiers:
•public - the property or method can be accessed from everywhere. This is default
•protected - the property or method can be accessed within the class and by
classes derived from that class
•private - the property or method can ONLY be accessed within the class
Example
• <?php
class Fruit {
public $name;
protected $color;
private $weight;
}
$mango = new Fruit();
$mango->name = 'Mango'; // OK
$mango->color = 'Yellow'; // ERROR
$mango->weight = '300'; // ERROR
?>
Static Properties
Static properties can be called directly - without creating an instance of a class.
Static properties are declared with the static keyword:
To access a static property use the class name, double colon (::), and the property name:
Syntax
ClassName::$staticProp;
Example
• <?php
class pi {
public static $value = 3.14159;
}
// Get static property
echo pi::$value;
?>
Static Methods
•
•
•
•
Syntax
ClassName::staticMethod();
Example
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
}
// Call static method
greeting::welcome();
?>
Inheritance
• It is a concept of accessing the features of one class
from another class. If we inherit the class features into
another class, we can access both class properties. We
can extends the features of a class by using 'extends'
keyword.
• It supports the concept of hierarchical classification.
• Inheritance has three types, single, multiple and multilevel
Inheritance.
• PHP supports only single inheritance, where only one class
can be derived from single parent class.
• We can simulate multiple inheritance by using interfaces.
• Example 1
<?php
class a
{
function fun1()
{
echo “Hello World";
}
}
class b extends a
{
function fun2()
{
echo “Devine";
}
}
$obj= new b();
$obj->fun1();
?>
Multilevel Inheritance:
• Multilevel inheritance involves a class inheriting from
a parent class, and that parent class itself inheriting
from another parent class. This forms a hierarchy or
class Animal {
chain of classes.
public function sound() {
echo "The animal makes a sound.";
}
}
class Mammal extends Animal {
// Additional class definition for Mammal
}
class Dog extends Mammal {
// Additional class definition for Dog
Hierarchical Inheritance:
• Hierarchical inheritance in php only occurs
when multiple classes inherit from a single parent
class. In this type of inheritance, one parent class
serves as the base class, and multiple child classes
derive from it.
class Shape {
public function area() {
// Code to calculate the area
}
}
class Circle extends Shape {
// Additional class definition for Circle
}
class Rectangle extends Shape {
// Additional class definition for Rectangle
}
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.
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
• When an exception is thrown, the code following it will
not be executed, and PHP will try to find the matching
"catch" block.
• <?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
checkNum(2);
?>
Try, throw and catch
Proper exception code should include:
1.try - A function using an exception should be in a "try" block. If the exception does not trigger,
2.the code will continue as normal. However if the exception triggers, an exception is "thrown"
2.throw - This is how you trigger an exception. Each "throw" must have at least one "catch"
3.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(2);
//If the exception is thrown, this text will not be
shown
echo 'If you see this, the number is 1 or below';
}
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>
Using Custom Exception Class
<?php
class myException extends Exception {
function get_Message() {
// Error message
$errorMsg = 'Error on line '.$this->getLine().
' in '.$this->getFile()
.$this->getMessage().' is number zero';
return $errorMsg;
}
}
function demo($a) {
try {
// Check if
if($a == 0) {
throw new myException($a);
}
}
catch (myException $e) {
// Display custom message
echo $e->get_Message();
}
}
// This will not generate any exception
demo(5);
// It will cause an exception
demo(0);
?>
Generic exception
PHP 5 has two built in exceptions
•Exception
•ErrorException
PHP 7 introduces new exceptions including catchable errors. New exceptions
include:
is the base interface for any object that can be thrown via a
• throw statement in PHP 7, including Error and Exception.
•Error is the base class for all internal PHP errors.
•AssertionError is thrown when an assertion made via assert() fails.
•ParseError is thrown when an error occurs while parsing PHP code, such as when eval() i
•Throwable
• Type error:
• Arithmetic error:
• DivisionByZeroError:
• ArgumentCountError:
• JSON exceptions:
•JsonException
is thrown when json_encode() and json_decode() experience an erro
Download