0% found this document useful (0 votes)
41 views21 pages

Intro To Oops Programming

The document discusses object oriented programming concepts like classes, objects, properties, methods and inheritance. It provides examples to demonstrate creating classes for student, employee and product with properties and methods. Constructors are used to initialize object properties. The $this keyword is used to refer to object properties and methods. Encapsulation, abstraction and polymorphism are some key features of OOP.

Uploaded by

Shubham Tilekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views21 pages

Intro To Oops Programming

The document discusses object oriented programming concepts like classes, objects, properties, methods and inheritance. It provides examples to demonstrate creating classes for student, employee and product with properties and methods. Constructors are used to initialize object properties. The $this keyword is used to refer to object properties and methods. Encapsulation, abstraction and polymorphism are some key features of OOP.

Uploaded by

Shubham Tilekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 21

1 . Introduction to Object Oriented Programming.

OOPs is object oriented programming language, OOPs handle real world


problem.
It refer to creation of reusable software object that can be easily
build multiple program.
OOPs is a collection of objects.
PHP provides support to OOPs Concepts, we can create class and object in
php.

*** Object ***


Object is real time entities.
Object is collections of variable(properties) and function(methods) all
group together in
single entity. The object can be created wherever needed, rather than
calling variable or function.
properties can hold information about the object and method are
manipulate data
within the object.
Each Object has its own properties. we can create n number of obj for a
class.

Syntax Creating object


$objnm= new classname(args);
e.g
$e1=new emp();
$e2=new emp(1,"Yashita",4566);

***** Class *****


Class is set of objects. or class collection variables(properties) and
methods(function) in single group.
Class is blueprint of the object.
Syntax
class clsname
{
properties;
methods;
};

//WAP to accept student details and display...


<html>
<body> <form method="post">
Enter Rollno :-><input type="text" name="t1"><Br>
Student Name :-><input type="text" name="t2"><Br>
Percentage :-><input type="text" name="t3"><Br>
<input type="submit" name="click " ><br>
</form>
<?php
if(isset($_POST['click']))
{
class student
{
var $rno,$name, $per; //variable declaration
function __construct($rno,$name,$per)
{
this->rno=$rno;
this->name=$name;
this->per=$per;
}
function display()
{
echo"<br> Student rollno->".$rno."<br> Student
name :->".$name."<br> Percentage =".$per;
}
}

echo "<br> Accept rollno, name and percentage :->";


$a=$_POST["t1"];
$b=$_POST["t2"];
$c=$_POST["t3"];
$s1=new student($a,$b,$c);
$s1->display();
}
else
{
echo" Kalatey ka ?";
}
?>
</body> </html>

-----------------------------------------------------------------------------------
-----------------
<html> <body> <form method="post">
Enter Rollno :-><input type="text" name="t1"><Br>
Student Name :-><input type="text" name="t2"><Br>
Percentage :-><input type="text" name="t3"><Br>
<input type="submit" name="click"><br>
</form>
<?php
if(isset($_POST['click']))
{
class student
{
var $rno,$name, $per;
function __construct($rno,$name,$per) // function _ _
construct()
{
$this->rno=$rno;
$this->name=$name;
$this->per=$per;
}
function display()
{
echo"<br> Student rollno->".$this->rno."<br> Student name :->".$this-
>name."<br> Percentage =".$this->per;
}
}
$a=$_POST["t1"]; $b=$_POST["t2"];
$c=$_POST["t3"];
$s1=new student($a,$b,$c);
$s1->display();
}
else
{
echo" Kalatey ka ?";
}
?>
-----------------------------------------------------------------------------------
--------------

//WAP to accept employee details(eid,ename and salary ) and display.


<html>
<body>
<form method="post">
Emp Id :-><input type="text" name="t1"><Br>
Emp Name :-><input type="text" name="t2"><Br>
Salary :-><input type="text" name="t3"><Br>
<input type="submit" name="click"><br>
</form>
<?php
if(isset($_POST['click']))
{
class employ
{
var $eno,$ename, $sal;
function accept($eno,$ename,$sal)
{
$this->eno=$eno;
$this->ename=$ename;
$this->sal=$sal;
}
function display()
{
echo"<br> Employee no->".$this->eno;
echo"<br> Emp name :->".$this->ename."<br> Salary =".
$this->sal;
}
}
$a = $_POST["t1"];
$b = $_POST["t2"];
$c = $_POST["t3"];
$e1=new employ;
$e1->accept($a,$b,$c);
$e1->display();
}
else
{
echo" Kalatey ka ?";
}
?>

Advantage of OOP
1) OOP provide a clear modular structure for program.
2) It is good to define abstract data type.
3) Implementation details are hidden from outside user and other modules has
clearly define interface.
4) It is easy to maintain and modify existing code as new object can be created
with small difference to existing ones.
5) Object, methods, instance, message passing, inheritance are some important
properties provided by the particular language.
6) Encapsulation, polymorphism, abstraction are also counts in this fundamental
of programming lang.
7) In OOPs programmer not only define data type but also deals with opeation
applied to data structures.

Features of OOP
1) More reliable software development is possible
2) Enhanced form of C programming lang
3) It support POP and OOP in nature
4) Much suitable for large project.

$this keyword
The keyword '$this' is used to refer to properties and method within the
class itself.
The pseudo-variable '$this' is available when a method is called from within
an object context.
$this is reference to calling object i.e it work like current object.

Syntax $this->properties . and $this->methodname();

Visibility mode( public , private and protected).

Accessing property and methods.


After object is instantiated, use hyphen and greater than sign (->) to
access method and variables
containing object.
$obj->property;
$obj->methodname(args);

// HW WAP to create class product to accept(pid,name,price and qty,


discount in per) accept
details and display cost after discount.
<!-- WAP to create class product to accept(pid,name,price and qty,
discount in per) accept details and display cost after discount. -->
<html>
<body>
<form method="post">
Product Id :-><input type="text" name="t1"><Br>
Product Name :-><input type="text" name="t2"><Br>
Price :-><input type="text"
name="t3"><Br>
Quantity :-><input type="text" name="t4"><Br>
Discount in per :-><input type="text" name="t5"><Br>
<input type="submit" name="click"><br>
</form>
<?php
if(isset($_POST['click']))
{
class product
{
var $pno,$pname, $p,$q,$d;
function accept($pno,$pname,$p,$q,$d)
{
$this->pno=$pno;
$this->pname=$pname;
$this->p=$p;
$this->q=$q;
$this->d=$d;
}
function display()
{
echo"<br> Product no->".$this->pno."<br> Product name :->".$this-
>pname."<br> Price =".$this->p."<br>Qty =".$this->q."<br>Discount =".$this->d;
$cost = ($this->p * $this->q)-($this->p * $this->q*
$this->d /100);
echo"<br> After discount cost =".$cost;
}
}
$a=$_POST["t1"];
$b=$_POST["t2"];
$c=$_POST["t3"];
$d1=$_POST["t4"];
$e=$_POST["t5"];
$p1=new product;
$p1->accept($a,$b,$c,$d1,$e);
$p1->display();
}
else
{
echo" Kalatey ka ?";
}
?>

-----------------------------------------------------------------------------------
----------------------------------------------------------

Purpose of Clone
Object Clone mean an object hold a reference to another object which it uses.

ie. by using clone we can create identical copy of existing object


When the parent object is replicated, a new instance of it is created so that
the replica
has its own separate copy.
An object copy is created using 'clone' keyword.

Syntax $obj=new clsname();


$copyobj= clone $obj;

<html>
<body>
<form method="post">
Emp Id :-><input type="text" name="t1"><Br>
Emp Name :-><input type="text" name="t2"><Br>
Salary :-><input type="text" name="t3"><Br>
<input type="submit" name="click"><br>
</form>
<?php
if(isset($_POST['click']))
{
class employ
{
var $eno,$ename, $sal;
function accept($eno,$ename,$sal)
{
$this->eno=$eno;
$this->ename=$ename;
$this->sal=$sal;
}
function display()
{
echo"<br> Employee no->".$this->eno."<br> Emp name :->".
$this->ename."<br> Salary =".$this->sal;
}
}
$a=$_POST["t1"];
$b=$_POST["t2"];
$c=$_POST["t3"];
$e1=new employ;
$e1->accept($a,$b,$c);
$e1->display();
echo"<br> Clone mean create duplicate object using existing object ---
><br>";
$e2=clone $e1;
$e2->display();
}
else
{
echo" Kalatey ka ?";
}
?>

-----------------------------------------------------------------------------------
------------------------------

*** Introspection**
Introspection is the ability of a program to examine an object's
characteristic, such as it name,parent class, properties, methods etc.
Introspection is applied to on classes as well as object.
At runtime, we can get information about classes, which help to write
debuggers, serializers profilers etc.

With introspection we can write code that operate on any class or object.
we need not know which methods or properties are define
when we write the code, instead, it can be discover at information at
runtime.
Examining Classes.
1) get_declared_classes() --> This function return an array of
define classes and checks if the classname is in the returned array.
2) class_exists(classname) --> Check class name is exist or not
3) get_class_methods(clsname) --> return class methods (including
those are inheritance from superclass)
4) get_class_vars(clsname) ---> return class variables including
superclass variable

Examining Object
1) is_object() --> This function to check whether the given variable
is object or not.
2) get_object_vars() ---> It returns an array of properties set in an
object. Return only those peroperties that are set.
3) get_parent_class() --> It return the name of parent if it exist,
otherwise return false.

29-09-2020
//WAP to demonstrate of instrospection of class and object. or give information
about class and object.
<?php
class rectangle
{
var $l=10;
var $b=20;
function rectangle($l, $b) // ha constructor define syntax in
old php version
{
$this->l=$l;
$this->b=$b;
}
function area()
{
return $this->l * $this->b;
}
function show()
{
echo " <br> Good morning.";
}
}
$r1=new rectangle(4,5);
$vars= get_class_vars("rectangle");
$obj= get_object_vars($r1);
$methods=get_class_methods("rectangle");
$objcls= get_class($r1);

echo"<br> Class variables -> "; print_r($vars);


echo"<br> Object property -> "; print_r($obj);
echo"<br> Methods Property -> "; print_r($methods);
echo"<br> Get class object -> "; print_r($objcls);
echo"<br> Get parent class ->
".get_parent_class("rectangle");
echo"<br> Check class exist -> ".class_exists("rectangle");
?>
----------x--------x---------x-----------x---------x--------x----------
x------------x-----------x----------x-------x-------------x----------------
x---------------x------------x-------------x---------------x----------x----------x-
Serialization
This function generate a storable representation of a value.
This is useful for storing or passing PHP values around without losing their
datatype and structure.
serialize() method used for converting PHP values to serialized String.

Syntax String serialize(mixed $value);

To turn back the serialized string into a PHP value, use unserialize();

When Serializing objects, PHP will attempt to call the member function
__sleep() prior to serialization.
This is allow the object to do any last minute clean-up etc. prior to being
serialized.

When the object is restored using unserialize() the __wakeup() member function
is called.
This function return a string containing a byte-stream representation of value
that can be stored in anywhere
<?php
class student
{
var $nm, $age, $course;
function __construct($a="rahul", $b=10, $c="BCS") //constructor
with default values
{
$this->nm=$a;
$this->age=$b;
$this->course=$c;
}
function getage()
{
return($this->age);
}
function getname()
{
return($this->nm);
}
function course()
{
return($this->course);
}
}
?>
<body bgcolor="orange">
<h1> Student Details </h1>
<?php

$s1=new student("Yashita",5,"MCA");
$p=new student();

$s2=serialize($s1);
print "<br><br> Serialized object string-->".$s2;
$p2=serialize($p);
print "<br><br> Serialized object string-->".$p2;

$s3=unserialize($s2);

$vay=$s3->getage();
$naav=$s3->getname();
$cor= $s3->course();

print "<bR> The student details are $naav and age is $vay years
and his course is $cor";

$t3=unserialize($p2);

$vay=$t3->getage();
$naav=$t3->getname();
$cor= $t3->course();

print "<bR> The student details are $naav and age is $vay years
and his course is $cor";
?>
Encapsulation
Binding or wrapping of properties and methods in single unit, It's keep safe
from outside misuser is called encapsulation.
All object are encapsulated-all code and required data are contained within the
object itself.
Encapsulated objects hide all internal code and data.
Encapsulated object allow users to see only the methods and properties of the
object that you allow them to see.
Its reduces the complexity of the code.
Encapsulation prevents other programmer from accidentally introducing a bug
into a program or stealing code.

e.g Medical capsule, Chocalate, school bag etc.


<?php
class demo
{
private $userid;
private $pwd;
public function updatepwd($userid, $pwd)
{
echo (" <Br> Function to update password".$pwd." for user ".
$userid);
}
function coursename($userid)
{
echo("<br> function to check course name of user :->".$userid);
}
}
$obj=new demo();
$obj->updatepwd('rahul','academy123');
$obj->coursename('india');
?>

*** Constructor ***


Constructor is special method, which is same name as classname. when object is
created constructor called automatically.
constructor are construct for to intialize value of variable.
constructor function commonly used in PHP to handle database connection
tasks.
constructor overloading doesnot support in PHP.
Syntax function classname(args) // PHP 4.
{
// defination of constructor
}
function __construct(args list)
{
//body of constructor.
}
There are two type of constructor
1) Default constructor :- constructor which has no arguments is
called default constructor.
2) Parameterized constructor :- constructor which has arguments is
called Parameterized constructor.
//WAP to demonstrate of parameterized constructor.
<?php
class rect
{
private $len, $breadth;
function __construct($len, $br)
{
echo"<br> Parameterized constructor ";
$this->len=$len;
$this->breadth=$br;
}
function area()
{
echo"<br> Area of rectangle ->".($this->len * $this->breadth);
}
}

$r1=new rect(10,20);
echo"<br> When object is created constructor called automatically";
$r1->area();
?>

-----------------------------------------------------------------------------------
--------------------
<?php
class student
{
private $rno, $snm, $per;
function __construct($rno,$snm,$per)
{
$this->rno=$rno;
$this->snm=$snm;
$this->per=$per;
}
function show()
{
echo"<br> Student rollno->".$this->rno."<br> Student name->".
$this->snm."<br> Student per->".$this->per;
}
};
$s=new student(1,"Vaishnavi",87);
11 $s->show();
?>

-----------------------------------------------------------------------------------
------------------------------------------------------------------

Destructor
When an object is destroyed, destructor called automatically. It's used for
release resources. some clean-up action
according to memory, objects, file closing, database closing etc.
destrctor has only default destructor.
A destructor function clean up any resources allocated to an object
after the object is destroyed.

A destructor function is commonly called in two way.


1) When a script ends.
2) when you manually delete an object with the unset() function.

Syntax function __destruct()


{
// body of destructor
}
//WAP to demonstrate of destructor
<?php
class rect
{
private $l,$b;
function __construct($l,$b)
{
$this->l=$l;
$this->b=$b;
}
function area()
{
echo"<bR> Area of rectangle :->".($this->l*$this->b);
}
function __destruct()
{
echo"<br> When object is destroyed, destructor called
automatically..../....";
}
}
$r1=new rect(5,7);
$r1->area();

$r1=null; //destructor called automatically


echo"<br> Kalatey ka?";
?>
-------x------------x--------------x----------------x-----------x----------------
x-------------x-----------------x--------------x--------------x-------------
x----------------x-------------x----------------x-------------x
06-10-2020
References
References in PHP are a mean to access the same variable content by differn
names. whenever we assign an object to another
variable, a copy of it is created.
<?php
$a=5;
$b= &$a;
for($i=0; $i<5; $i++)
{
echo"<br> Value of a is : $a and value of reference b is : $b";
$a++;
$b--;
}
?>

Passing by reference allow us keep the new variable "Linked" to original source
variable. Changes to either the new variable or
old varaible will be reflected in the value of both.
<?php
$col='black';
$set['key']= &$col;
$col='white';
echo" <br> Original variable change then reference value also change ->".
$set['key']; //white
?>

Reference inside the constructor.


Creating references within constructor can lead to confusing result.
Apparently there is no difference, but in fact there is very significant one.
$obj and glovar[0] are not referenced. they are not the same variable. This is
because 'new' doesnot return a reference by default
instead it return a copy.
<?php
class refcon
{
function __construct($nm)
{
global $glovar;
$glovar[]=&$this;
$this->setname($nm);
$this->echoname();
}
function echoname()
{
echo"<br> Name-->".$this->nm;
}
function setname($nm)
{
$this->nm=$nm;
}
}
$obj=new refcon(' INDIA ');
$obj->echoname();
$glovar[0]->echoname();
?>

**** Inheritance ****


one class object aquaire the properties of another class object, with it own
property is called inheritance.
Inheritance is the abliity of php to extend classes(Child class) that inherit
the characteristics of the parent class.
The resulting object of an extends class has all the characteristic of parent
class plus whatever is in the new child class.
A class can inherit the methods and properties of another class by using
'extends' keyword.

The inheritance methods and properties can be overridden by re-declaring them


with the same name defined in the parent
class. However, if the parent has define a method as final, that method may
not be overridden.

In php there are 3 type inheritance..


1) Single inheritance : one child has only one base class is called single
inheritance. child class access properties of parent
class. vice versa is not possible
class base
{
// methods, properties
}
class derive extends base
{
// methods, properties
}
//WAP to demonstrate of single inheritance..
<?php
class fruit
{
public $nm;
public $color;
public function __construct($nm, $color)
{
$this->nm=$nm;
$this->color=$color;
}
protected function demo()
{
echo" <br> The Fruit is $this->nm and color is $this-
>color";
}
}
class mango extends fruit
{
public function sample()
{
echo"<bR> Hello I am Mango ";
$this->demo();
}
}
$obj=new mango("Hapusmango","yellow");
$obj->sample();
// $obj->demo();
?>

-----------------------------------------------------------------------------------
-------------------------------
//WAP to overridden display method is base and derive class. access by
using (::) operator
Syntax
classname :: methodname();
or
parent :: methodname();
<?php
class base
{
public $a='Good Morning Everybody..';
function display()
{
echo"<br> Hello I am base class display method -->";
echo"<br>".$this->a;

}
}
class derive extends base
{
function display()
{
base :: display();
echo"<br> Hello I am Derive class display method -->";
echo"<br>".$this->a;
echo"<br> It is possible to access to overridden methods or static
properties by referring them with parent:: " ;
parent::display();
}
}
$d1=new derive();
$d1->display();
?>
-----------------------------------------------------------------------------------
-------------------------------------------------------------------
Multilevel Inheritance..
One Derive class is inherite from another derived class is called multilevel
inheritance.
class A // Grandparent
{
// properties and methods.
}
class B extends A // Parent class
{
// properties and methods.
}
class C extends B // Child class.
{
// properties and methods.
}

-----------------------------------------------------------------------------------
--------------------------------------------------
// WAP to demonstrate of multilevel inheritance...
<?php
class grandparent
{
public function gage()
{
echo"<br> <font color=red> Age of grand parent is : 75 </font>";
}
}
class parent1 extends grandparent
{
public function page()
{
echo"<br> <font color=green> Age of parent is : 50 </font>";
}
}
class child extends parent1
{
public function cage()
{
echo"<br> <font color=blue> Age of Child is : 25 </font>";
}
public function show()
{
grandparent::gage();
parent1::page();
$this->cage();
}
}
$c1=new child();
$c1->show();
echo"<br> Directly access.";
$c1->gage();
$c1->page();
$c1->cage();
?>
-----------------------------------------------------------------------------------
-----------------------------------
**** Hierarchical Inheritance ***
One base class has two or more derive classes is called hierarchical
inheritance.
<!-- WAP php script to create class shape and it's subclass tringle, square and
circle. and display the area of selected shape. -->
<?php
class shape
{
public $x,$y;
function getdata($x,$y)
{
$this->x=$x; $this->y=$y;
}
}
class tringle extends shape
{
function area()
{
echo"<br> Area of tringle ->".(0.5 * $this->x * $this ->y);
}
}
class square extends shape
{
function area()
{
echo"<br> Area of square ->".( $this->x * $this ->x);
}
}
class circle extends shape
{
function area()
{
echo"<br> Area of circle ->".( 3.14 * $this->x * $this ->x);
}
}
$t1=new tringle();
$t1->getdata(5,6); $t1->area();

$s1=new square();
$s1->getdata(10,0); $s1->area();

$c1=new circle();
$c1->getdata(5,0); $c1->area();
?>

-----------------------------------------------------------------------------------
--------------------------------------------------
Scope Resolution Operator
The scope resoluation operator (::) also called Paamayim Nekudotayim. ie.
double colon. is a token that allows access to static, constant,
overridden member or methods of class.
<?php
class demo
{
const a="India is my country.";
}
echo "<br> Msg :->".demo :: a;
?>
Syntax
classname :: constvariablename;
By using (::) operator we can access const var outside the class.

<?php
class base
{
const a="India is my country.";
}
class derive extends base
{
function display()
{
echo " base cls ==>". parent::a;
}
}
$d1=new derive();
$d1-> display();
?>

-----------------------------------------------------------------------------------
------------------------
Access Specifiers (public, private, protected)
public access specifiers.
This allows anyone to call a class's member function or modify a data
member.
By default alll cls member are public.
public class member are available through-out the script and may be
accessed from outside class.

private access specifier.


This prevents objects from calling member function or accessing data
member and is one of key elements in information hidding.
Private access doesnot restrict a class internal acces to the members.
private access restrict object from accessing cls member.

Protected access specifier.


protected methods and properties are available only to the related
classes. used in inheritance.

<?php
class add
{
protected $n;
public function setno($n)
{
$this->n=$n;
}
}
class divide extends add
{
public function demo()
{
$div=$this->n/2;
echo"<br> Division =".$div;
}
}
$d1=new divide();
$d1->setno(50);
$d1->demo();
?>
-----------------------------------------------------------------------------------
------------------------------------------------------------
final
This is used to protect your code from being used to improper manner.
Any method or class declared as final, final method cannot be
overriedden(redefine in subcls).
final class can't be extended..i.e final class doesnot inherited by anothe
class.
final variable create as constant.

-----------------------------------------------------------------------------------
-------------------------------
Abstract Class and methods.
Abstarct class is incomplete class, because we cannot create object of abstract
class.
abstract class use for or serve for subclass. It contains some method
declaration and some method defination.
The method which has no body is called abstract methods.
abstract method must be override in his subclass.
if we declare abstact method in class. that class must be declare as abstract.
Syntax abstract class clsname
{
abstaract method declaration();. //abstact method.
function fname(args)
{
}
}
<?php
abstract class sample
{
public $x, $y;
function getdata($x,$y)
{
$this->x=$x; $this->y=$y;
}
abstract function show();
}
class demo extends sample
{
function display()
{
echo"<br> Hello Good evening...";
}
function show()
{
echo"<br> Multiplication of two number :->".($this->x * $this->y);
}
}
$d1=new demo();
$d1->getdata(6,8);
$d1->display();
$d1->show();
?>
<!-- Write PHP program to create abstract class college. it contains $nm, $code,
$course, create abstract method show.
and derive class science from it with accept and show details. accept info
from user and assign class member and print. -->
<html>
<body>
<form method ="post">
Enter the College Name <input type="text" name ="t1"><br>
Enter the College Code <input type="text" name ="t2"><br>
Enter Course Name <input type="text" name ="t3"><br>
<input type="submit" name ="sub" value="click">
</form>
<?php
abstract class college
{
public $cnm,$code,$course;
function accept($cnm, $code,$course)
{
$this->cnm=$cnm;
$this->code=$code;
$this->course=$course;
}
abstract function show(); //abstract method declare keli aahe.
}
class science extends college
{
function show()
{
echo"<b> College name=".$this->cnm."<br> Code=".$this->code."<br>
Course :->".$this->course;
}
}
$s1=new science();
if(isset($_POST['sub']))
{
$cnm = $_POST['t1']; $c = $_POST['t2']; $course =
$_POST['t3'];
$s1->accept($cnm,$c,$course);
$s1->show();
}
?>

Static method and properties(variables) .


The use of static keyword allow class member(properties and method) to be
used to without needing object of the class.
static variable create only one copy. that copy can shear no of object of
the same class.
static variable doesnot belong any object, it Belong to class. so therefore
static variables access by using classname or 'self' Keyword.
Syntax
classname:: varname; or self::varname;

Declaration syntax public static $staticvar;


e.g public static $cnt;

Static method.
Static method is used to initialize static variables. This method
doesnot belong any object. it belong to class.
therefore we cannot create any object using a static call. ie. object is
not required for static method.
the keyword $this and -> we cannot use in static call.
To access within the class itself you need to use self keyword along
with the :: operator
self :: varname; or self ::
methodname;

<?php
class static1
{
static $cnt; //declaration
}
static1 :: $cnt=" U can initialize static variable ";
//initialization
echo"<br> <h2> Static variable display ".static1::$cnt;
//access static variable
?>

//WAP to count no of object by using static variable. and define static method
show().
<?php
class counter
{
private static $cnt=0;
function __construct()
{
self::$cnt++;
}
public static function getcount()
{
echo"<br> No of object Created->".self::$cnt;
}
}
$a1=new counter();
counter::getcount();
$a2=new counter();
counter::getcount();
$a3=new counter();
counter::getcount();
?>

******** Interface *************


Interface is pure abstract class. we can declare constant and method
declaration in interface.
We cannot create object of interface. but we can reference of interface.
declare methods in interface, by default abstract methods.
and we know abstract method i.e interface method must be override in subclass.
Interface provides method prototype and constant, and any class implements the
interface must provide implamentation of all
method of interface. .

Syntax
interface interfacename
{
function functioname1();
function functioname2();
function functioname3();
|
|
}

To declare that a class implements an interface, include 'implements' keyword


and any number of interface, separated by commas.

Primary purpose of interface


i) Interface allow us to define/create a common structure for our sub
classes-to set a standard for objects.
ii) An interface solves the problem of single inheritance, they allow us
to inject 'qualities' from multiple source.
iii) Interface provide a flexible base/root structure that we don't get
with classes.
iv) Inteface are great when we have multiple coders working on a projects.

Difference between abstract class and interface in php


i) In abstract classes it is not necessary that every method should be
abstract. But in interface every method is abstract.
ii) Multiple and multilevel both type of inheritance is possible in
interface. but single and multilevel inheritance is possible in abstract classes.
iii) Method of PHP interface must be public only. method of abstract class
in php could be public or protected both.
iv) In abstract class we can define as well as declare methods. but in
interface we can only declare our methods.
<!-- WAP to demonstrate of interface , create muliple inheritance. -->
<?php
interface A
{
function getmsg();
}
interface B
{
function getinfo();
}
interface C
{
function show();
}
class Demo
{
function display()
{
echo"<br> One base class and others classes are
interface";
}
}
class D extends Demo implements A,B,C
{
function getmsg()
{
echo"<br> By interface we can achieve multiple
Inheritance";
}
function getinfo()
{
echo"<br> Interface Methods must be override in
subclass";
}
function show()
{
echo"<br> method of interce must be in public";
}
}
$d1=new D();
$d1->display();
$d1->getmsg(); $d1->getinfo(); $d1->show();
?>

<!-- Write a PHP script to create interface testdrive contains two methods
getdata() and show(). create class bike implements from
testdrive. Override getdata(), and show() method. accept details and display
-->
<?php
interface testdrive
{
function getdata($a,$b,$c); //only method declaration
function show();
}
class bike implements testdrive
{
public $brand, $color,$price;
function __construct()
{
echo"<br> Bike details ->";
}
function getdata($a,$b,$c)
{
$this->brand=$a; $this->color=$b; $this->price=$c;
}
function show()
{
echo"<br><h2> Bike Name=".$this->brand."<br> Bike Color =".$this-
>color."<br> Bike Price=".$this->price."<br>" ;
}
}
$obj= new bike();
$obj->getdata("Bullet","Black",12345);
$obj->show();
?>

Homework
1) Write PHP program to create class employee(eno,ename,sal, designation). with
member function acceptdata, display
data and display max salary. Display data of employee.

2) Write a PHP script to create class shape and its subclasses triangle, square ,
and circle. display are of selcted shape.
( use radio button for different shape. Use inheritance.)

3) write a PHP script to accept student(rno,snm,class) and print it in sorted


order by name.

You might also like