Intro To Oops Programming
Intro To Oops Programming
-----------------------------------------------------------------------------------
-----------------
<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 ?";
}
?>
-----------------------------------------------------------------------------------
--------------
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.
-----------------------------------------------------------------------------------
----------------------------------------------------------
Purpose of Clone
Object Clone mean an object hold a reference to another object which it uses.
<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);
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.
$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.
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
?>
-----------------------------------------------------------------------------------
-------------------------------
//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.
<?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.
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();
?>
Syntax
interface interfacename
{
function functioname1();
function functioname2();
function functioname3();
|
|
}
<!-- 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.)