Unit III
Unit III
Teaching
Theory Practical
Scheme
Credit
(L+T+P) Paper ESE PA TOTAL ESE PA TOTAL
L T P
hrs. Max Min Max Min Max Min Max Min Max Min Max Min
Course Outcomes:
a. Develop Program using Control Statements.
b. Perform operations based on arrays and graphics.
c. Develop Program by applying various object oriented concepts.
d. Use form controls with validation to collect user’s input.
e. Perform database operations in PHP
Index
S.N. Description TH No. of
Understanding Marks Hrs Pr
Level
Units 70 48 16
1. Expressions & Control Statements in PHP Easy 12 06 3
2. Arrays, Functions & Graphics Medium 16 10 4
3. Apply Object Oriented Concepts in PHP Medium 16 12 2
1 4. Creating & Validating Forms Medium 12 12 5
5. Database Operations Medium 14 08 2
2 Assignments 5
50
3 Practice questions-Unit Tests
Questions
5Q-2M ,5Q-4M
3b
Implement Inheritance to extends to given base class.
3c
Use overloading / overriding to solve the given problem.
3d
Clone the given object.
Class
- A class is defined by using the class keyword, followed by the
name of the class and a pair of curly braces ({}).
- All its properties and methods go inside the braces:
Syntax :
<?php
class classname {
// code goes here...
}
?>
<?php
class classname {
// Properties
//variable declaration
public $variable1;
public $variable2;
// Methods
function method1($variableN) {
$this->variable1 = $variableN;
}
function method2() {
return $this->variable1;
}
}
?>
Objects
Syntax :
Example :
The $this keyword refers to the current object, and is only available
inside methods.
Example
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
?>
we can change the value of the variables of class (e.g.$name property) by two ways:
Example
<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit);
?>
● Constructor
- A constructor allows to initialize an object of class.
- It is automatically called when we create an object of
class.
- Constructor is created using a “ __construct()” function.
- It can be default or parameterized.
Syntax:
1. Constructor with no argument 2. Constructor with argument
{ {
//code //code
} }
Constructor with Zero Argument
<?php
echo "Hello ,Welcome to OOP Concepts!<br>";
class emp
{
public $id;
public $n;
function __construct() //constructor with no argument
{
$this->id=200;
$this->n="abc";
}
function disp()
{
echo "ID : $this->id<br>";
echo "Name: $this->n<br>";
}
}
echo "Lets use emp class<br>";
$e=new emp(); //constructor will be called
$e->disp();
echo "Thank you!<br>";
?>
Constructor with Argument
<?php
echo "Hello ,Welcome to OOP Concepts!<br>";
class emp
{
public $id;
public $n;
function __construct($i,$nm) //constructor with argument
{
$this->id=$i;
$this->n=$nm;
}
function disp()
{
echo "ID : $this->id<br>";
echo "Name: $this->n<br>";
}
}
echo "Lets use emp class<br>";
$e=new emp(12,"xyz"); //constructor with arg will be called
$e->disp();
echo "Thank you!<br>";
?>
● Destructor
- A destructor is used to destroy the object or cleanup the object memory.
- called when the the script is exited. created using a ”__destruct()” function.
- PHP will automatically call this function at the end of the script.
- destruct function starts with two underscores (__)
Syntax:
function __destruct( )
{
//code
}
Destructor
<?php
echo "Hello ,Welcome to OOP Concepts!<br>";
class emp
{
public $id;
public $n;
function __construct($i,$nm) //constructor with argument
{ $this->id=$i;
$this->n=$nm;
}
function disp()
{
echo "ID : $this->id<br>";
echo "Name: $this->n<br>";
}
function __destruct()
{
echo "---Bye----";
}
}
echo "Lets use emp class<br>";
$e=new emp(12,"xyz"); //constructor will be called
$e->disp();
echo "Thank you!<br>";
?>
Access Modifiers
Properties and methods can have access modifiers which control
where they can be accessed.
There are three access modifiers:
● private - the property or method can ONLY be accessed
within the class
● 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
public access specifier for variable
<?php
echo "Hello ,Welcome to OOP Concepts!<br>";
class emp
{ public $id;
public $n;
function __construct($i,$nm) //constuctor with argument
{
$this->id=$i;
$this->n=$nm;
}
function disp()
{
echo "ID : $this->id<br>";
echo "Name: $this->n<br>";
}
}
echo "Lets use emp class<br>";
$e=new emp(12,"xyz"); //constructor will be called
$e->disp();
$e->id=300; //public variables are accessible using object
$e->n="LMN";
$e->disp();
echo "Thank you!<br>";
?>
public access specifier for function
<?php
echo "Hello ,Welcome to OOP Concepts!<br>";
class emp
{ public $id;
public $n;
function __construct($i,$nm) //constuctor with argument
{
$this->id=$i;
$this->n=$nm;
}
public function disp()
{
echo "ID : $this->id<br>";
echo "Name: $this->n<br>";
}
}
echo "Lets use emp class<br>";
$e=new emp(12,"xyz"); //constructor will be called
$e->disp(); //public function accessible using object
$e->id=300;
$e->n="LMN";
$e->disp();
echo "Thank you!<br>";
?>
private access specifier for variable
<?php
echo "Hello ,Welcome to OOP Concepts!<br>";
class emp
{ private $id;
public $n;
function __construct($i,$nm) //constuctor with argument
{
$this->id=$i;
$this->n=$nm;
}
function disp()
{
echo "ID : $this->id<br>";
echo "Name: $this->n<br>";
}
}
echo "Lets use emp class<br>";
$e=new emp(12,"xyz"); //constructor will be called
$e->disp();
$e->id=300; //privare variables not accessible using object
$e->n="LMN";
$e->disp();
echo "Thank you!<br>";
?>
● Inheritance
- When a class derived from another class.
- The child class will inherit all the public and protected properties and methods from the
parent class.
- An inherited class is defined by using the extends keyword.
Syntax:
<?php
class baseclassname { //code
}
class derivedclassname extends baseclassname
{ //code
}
//code
?>
Single Inheritance
Example:
<?php
class A
{ public $n;
function set()
{ $this->n="Priti";
}
}
class B extends A
{ function disp()
{ echo "Welcome $this->n";
A
}
}
$b=new B();
$b->set(); B
$b->disp();
?>
Multilevel Inheritance
Example:
<?php
class A
{public $n;
function set(){ $this->n="Priti"; }
}
class B extends A
{function disp(){ echo "Welcome $this->n<br>"; }
A
}
class C extends B
{function show() { echo "Bye $this->n"; }
} B
$ob=new C();
$ob->set();
$ob->disp();
C
$ob->show();
?>
Hierarchical Inheritance
<?php
class A
{public $n;
function set()
{ $this->n="Priti"; }
}
class B extends A
{
function disp() { echo "Welcome $this->n<br>"; }
}
class C extends A A
{function show()
{ echo "Bye $this->n";
}
}
B C
$ob1=new B();
$ob2=new C();
$ob1->set(); //B class has called function set so its not working for ob2 object of C class
$ob1->disp();
$ob2->show();
?>
Hierarchical Inheritance
<?php
class A
{public $n;
function set()
{ $this->n="Priti"; }
}
class B extends A
{
function disp() { echo "Welcome $this->n<br>"; }
}
class C extends A A
{function show()
{ echo "Bye $this->n";
}
}
B C
$ob1=new B();
$ob2=new C();
$ob2->set(); //C class has called function set so its not working for ob1 object of B class
$ob1->disp();
$ob2->show();
?>
Method Overriding :
Method overriding means when a base and derived class having same method with same
signature;then the method in derived class overrides the method in base class.
The method in the base/parent class is called overridden method, while the method in the
child/derived class is known as the overriding method. The code in the overriding
method overrides (or replaces) the code in the overridden method.
PHP will decide which method (overridden or overriding method) to call based on the
object used to invoke the method.
● If an object of the parent class invokes the method, PHP will execute the overridden
method.
● But if an object of the child class invokes the method, PHP will execute the
overriding method.
<?php
class A
{
public $n;
function show()
{ echo "Hi";
}
}
class B extends A
{
function show()
{ echo "Bye";
}
}
$ob=new B();
$ob->show();
?>
<?php
class A
{
public $n;
function show()
{ echo "Hi<br>";
}
}
class B extends A
{
function show()
{ parent::show(); //calls show() function of parent/super/base class
echo "Bye<br>";
}
}
$ob=new B();
$ob->show();
?>
The final Keyword
Syntax:
<?php
final class base-class-name
{ // code
}
{ // code
}
?>
<?php
final class A
{
public $n;
function show()
{
echo "Hi<br>";
}
}
class B extends A //gives error
{
function show()
{
echo "Bye<br>";
}
}
$ob=new B();
$ob->show();
?>
Constants
● Constants can be useful if you need to define some constant data within a class.
● A constant is declared inside a class with the const keyword.
● A constant cannot be changed once it is declared.
● Class constants are case-sensitive.
● it is recommended to name the constants in all uppercase letters.
We can access a constant from inside the class by using
the self keyword followed by the scope resolution operator (::)
followed by the constant name, like here:
<?php
class Goodbye {
const MESSAGE = "Thank you for visiting!";
public function bye() {
echo self::MESSAGE;
}
}
$g = new Goodbye();
$g->bye();
?>
We can access a constant from outside the class by using the class
name followed by the scope resolution operator (::) followed by the
constant name:
<?php
class Goodbye {
const MESSAGE = "Thank you for visiting!";
}
echo Goodbye::MESSAGE;
?>
Abstract Classes
● An abstract class is a class that contains at least one abstract method.
● Abstract classes and methods are when the parent class has a named
method, but need its child class(es) to fill out the tasks.
● An abstract method is a method that is declared, but not implemented in
the code.
● Example:
Shape
area( )
Circle Rectangle
area( ) area( )
● An abstract class or method is defined with the abstract keyword.
abstract class Car
So, when a child class is inherited from an abstract class, we have the following
rules:
● The child class method must be defined with the same name and it redeclares
the parent abstract method
● The child class method must be defined with the same or a less restricted access
modifier.
Characteristics of abstract class:
• It can have both regular methods( with implementations) and abstract
methods (without any implementation. )
• They serve as placeholders, ensuring that any class extending the abstract class
provides an implementation for those methods.
• Abstract class in php are useful when you want to define a common interface or
behavior that multiple related classes should have.
• They provide a level of abstraction.
• Object of abstract class can not be created.
<?php
abstract class Student
{
public $rn;
public function setRollNo($rollno)
{
$this->rn = $rollno;
echo "Roll No:$this->rn <br>";
}
abstract public function favouriteSubject();
}
class ABC extends Student
{
public function favouriteSubject()
{
echo " favourite Course : English";
}
}
$obj = new ABC; //this statement does not throws error and executes correctly
$obj->setRollNo(12);
$obj->favouriteSubject();
?>
<?php
class shape
{
public $r;
function area(); //trying to declare method and not writing body
}
class circle extends shape
{
function area()
{
$this->r=4;
$ac=3.14*$this->r*$this->r;
echo "Area of circle: $ac";
}
}
class rectangle extends shape
{
function area()
{
$this->l=4;
$this->b=3;
$ar=$this->l*$this->b;
echo "Area of Square: $ar";
}
}
echo "----------Calculating Area of Shape----<br>";
$c=new circle();
$c->area();
$r=new rectangle();
$r->area();
echo "--------Thank you----------<br>";
?>
<?php
class shape
{
public $r;
abstract function area(); //declaring method as abstract
}
class circle extends shape
{
function area()
{
$this->r=4;
$ac=3.14*$r*$r;
echo "Area of circle: $ac";
}
}
class rectangle extends shape
{
function area()
{
$this->l=4;
$this->b=3;
$ar=$l*$b;
echo "Area of Square: $ar";
}
}
echo "----------Calculating Area of Shape----<br>";
$c=new circle();
$c->area();
$r=new rectangle();
$r->area();
echo "--------Thank you----------<br>";
?>
<?php
class shape
{
public $r;
abstract function area(); //declaring method as abstract
}
class circle extends shape
{
function area()
{
$this->r=4;
$ac=3.14*$this->r*$this->r;
echo "Area of circle: $ac";
}
}
class rectangle extends shape
{
function area()
{
$this->l=4;
$this->b=3;
$ar=$this->l*$this->b;
echo "Area of Square: $ar";
}
}
echo "----------Calculating Area of Shape----<br>";
$c=new circle();
$c->area();
$r=new rectangle();
$r->area();
echo "--------Thank you----------<br>";
?>
<?php
abstract class shape //declared class as abstract
{ public $r;
abstract function area(); //declared function as abstract
}
class circle extends shape
{ function area()
{ $this->r=4;
$ac=3.14*$this->r*$this->r;
echo "Area of circle: $ac<br>";
}
}
class rectangle extends shape
{
function area()
{ $this->l=4;
$this->b=3;
$ar=$this->l*$this->b;
echo "Area of Square: $ar<br>";
}
}
echo "----------Calculating Area of Shape----<br>";
$c=new circle();
$c->area();
$r=new rectangle();
$r->area();
echo "--------Thank you----------<br>";
?>
Multiple Inheritance
A B
Show() Show()
C
Show()
A B
Show() Show()
C
Show()
Interface
Interfaces
● Interfaces allow you to specify what methods a class should implement.
● Interfaces are declared with the interface keyword:
Syntax
<?php
interface InterfaceName {
public function someMethod1();
public function someMethod2();
}
?>
To implement an interface, a class must use the implements keyword.
class classname implements interfacename {
public function someMethod1() {
//code
}
}
<?php
interface WebApp
{
public function login($email, $password);
public function logout();
}
class testapp implements WebApp
{
public function login($email, $password)
{ echo "Login the user with email: " . $email;
}
public function logout()
{ echo "<br>User logged out!";
}
}
$ob=new testapp();
$ob->login("[email protected]",123);
$ob->logout();
?>
<?php
class A
{
function show()
{ echo "Hi<br>";
}
}
interface B
{ function show();
}
class C extends A implements B
{
function show()
{ echo "Bye<br>";
}
}
$ob=new C();
$ob->show();
echo "--------Thank you----------<br>";
?>
Interface Characteristics:
•All the methods declared in the interfaces are public and do not
start with the abstract keyword.
•If we miss to implement even a single method declared in the
interface, in the class implementing the interface, we will get an
error.
•Interfaces do not have variables.
Interface Class
All methods in an interface are abstract All methods need not to be an abstract
Traits are more suitable for code reuse across Interfaces are more suitable for defining
unrelated classes. contracts and achieving abstraction and
polymorphism.
Traits allow for horizontal code reuse, Interfaces provide a way to achieve vertical
meaning that they enable the sharing of code code reuse, allowing classes to implement
between unrelated classes. multiple interfaces.
Traits can define methods, properties, or both. Interfaces can only define method signatures,
not properties.
Traits promote cleaner, more maintainable Using interfaces promotes loose coupling and
code by reducing code duplication and abstraction.
enabling the composition of behavior.
Traits offer flexibility as they can be easily Interfaces enforce good programming
added or removed from classes. practices, and design patterns, and improve
testability.
You can use multiple traits in a single class. One class can implement multiple Interfaces
Static variable
Static variables are declared with ‘static’ keyword.
Syntax :
<?php
class ClassName
{
public static $var=value;
public function Methodname( )
{ //code
}
}
?>
Static variable Characteristics:
Syntax :
<?php
class ClassName
{
public static function Methodname( )
{
//code
}
}
?>
To access a static method use the class name, double colon
that is scope resolution(::), and the method name:
Syntax
ClassName::Methodname();
It means there will be only one copy of static function, no any further
function can have same name and same signature
<?php
class SI
{ public $p; //instance
public $n; //instance
public static $r=8.5; //static property
public function set($a,$y) // non-static function
{
$this->p=$a;
$this->n=$y;
}
public function cal() //non-static function
{ $ans=($this->p*$this->n*SI::$r)/100;
echo "<br>Simple Interest : $ans<br>";
}
}
echo "<br> welcome to Bank <br>";
$c1=new SI(); non-static function can
$c1->set(200000,3);
$c1->cal(); access instance and static
$c2=new SI();
$c2->set(800000,4); properties(variables)
$c2->cal();
echo "<br> Thank You <br>";
?>
<?php
class SI
{ public $p; //instance
public $n; //instance
public static $r=8.5; //static property
public static function set($a,$y) // static function
{
$this->p=$a;
$this->n=$y;
}
public function cal() //non-static function
{ $ans=($this->p*$this->n*SI::$r)/100;
echo "<br>Simple Interest : $ans<br>";
}
}
echo "<br> welcome to Bank <br>";
$c1=new SI(); static function can access
$c1->set(200000,3);
$c1->cal(); only static
$c2=new SI();
$c2->set(800000,4); properties(variables)
$c2->cal();
echo "<br> Thank You <br>";
?>
<?php
class SI
{
public static $r=8.5; //static property
public static function show()
{echo "From Self class ROI = ".SI::$r;
}
}
class x extends SI
{
• static function can be accessed
public function disp() inside class using –
{ echo "<br> From Derived value of ROI :";
echo parent::$r;
classname::$varname
} or
}
echo "<br> welcome to Bank <br>";
self ::$varname
SI::show(); • From derived class ,static
$o=new x();
$o->disp();
variable can be accessed using-
echo "<br> Thank You <br>"; classname ::$varname
?>
or
parent ::$varname
clone :
Function Description
class_exists() Checks whether a class has been defined.
get_class() Returns the class name of an object.
get parent_class() Returns the class name of a Return object's parent class.
}
}
$c = get_declared_classes();
echo "The following classes are available:<br>";
print_r($c);
?>
<?php
class A
{ public $x;
public function dispA() { echo "I am a super class <br>"; }
}
class B extends A
{ public $n;
public function dispB() { echo "welcome<br>"; }
}
$c = get_declared_classes();
if (in_array("B", $c))
print "Class A is available <br>";
$b = new B();
$m = get_class_methods($b);
echo "The following methods are available:<br>";
print_r($m);
$vars = get_class_vars("B");
echo "<br>The following properties are available:<br>";
print_r($vars);
?>
Serialization in PHP
- Serialization is a technique used by programmers to preserve their working data in a format
that can later be restored to its previous form.
- Serializing an object means converting it to a byte stream representation that can be stored in
a file.
- Serialization in PHP is mostly automatic, it requires little extra work from you, beyond calling
the serialize() and unserialize() functions.
Serialize():
- The serialize() converts a storable representation of a value.
- The serialize() function accepts a single parameter which is the data we want to serialize and
returns a serialized string.
- A serialize data means a sequence of bits so that it can be stored in a file, a memory buffer, or
transmitted across a network connection link.
It is useful for storing or passing PHP values around without losing their type and structure.
Syntax:
serialize(value);
unserialize():
unserialize() can use string to recreate the original variable values i.e. converts actual data
from serialized data.
Syntax: unserialize(string);
Example:
<?php
$a=array('Shivam','Rahul','Vilas');
$s=serialize($a);
print_r($s);
$s1=unserialize($s);
echo "<br>";
print_r($s1);
?>
Output:
a:3:{i:0;s:6:"Shivam";i:1;s:5:"Rahul";i:2;s:5:"Vilas";}
Array ( [0] => Shivam [1] => Rahul [2] => Vilas )
<?php
$a="Priti";
$s=serialize($a);
print ($s);
$s1=unserialize($s);
echo "<br>";
print ($s1); For String
?> variable
<?php
$a=100;
$s=serialize($a);
print ($s);
$s1=unserialize($s);
echo "<br>";
print ($s1); For Numbers
?>
THANK YOU