0% found this document useful (0 votes)
3 views

Chapter 3-Apply Object Oriented Concepts in PHP

Chapter 3 discusses Object-Oriented Programming (OOP) in PHP, highlighting its advantages over procedural programming, such as improved structure and reusability. It covers key concepts including classes, objects, constructors, destructors, inheritance, method overloading, and introspection, providing syntax and examples for each. The chapter emphasizes the importance of OOP principles in creating efficient and maintainable PHP applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter 3-Apply Object Oriented Concepts in PHP

Chapter 3 discusses Object-Oriented Programming (OOP) in PHP, highlighting its advantages over procedural programming, such as improved structure and reusability. It covers key concepts including classes, objects, constructors, destructors, inheritance, method overloading, and introspection, providing syntax and examples for each. The chapter emphasizes the importance of OOP principles in creating efficient and maintainable PHP applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

Chapter 3:

Apply Object Oriented


Concepts in PHP
PHP What is OOP?
•OOP stands for Object-Oriented Programming.
•Procedural programming is about writing procedures or functions
that perform operations on the data, while object-oriented
programming is about creating objects that contain both data and
functions.

•Object-oriented programming has several advantages over


procedural programming:
1.OOP is faster and easier to execute
2.OOP provides a clear structure for the programs
3.OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and
makes the code easier to maintain, modify and debug
4.OOP makes it possible to create full reusable applications with less
code and shorter development time
Class:
•A PHP class is a group of values with a set of
operations to manipulate this values.
•Class facilitate modularity and information
hiding.
•Classes are used to define a new data type
Rules
•The class name can be any valid label.
•It can’t be PHP reserved word.
•A valid class name starts with a letter or
underscores, followed by any number of letter,
numbers or underscores.
Syntax:
class classname
{
var $variable_name;
var $variable_name;
function function_name()
{
body of method;
}
}
Example:
class Mobile
{
public $model;
function showModel($number)
{
$this->model=$number;
echo “Model Number: $this->model”;
}
}
Note :
•You can’t assign computed value inside a class.
Example: public $price=10+20;
public $name=“ABC”.”XYZ”;
•You can’t begin the name of method with a double underscore
__
Object :
•Object is class type variable.
•Each time you create an object of a class a copy of each variables
defined in the class is created. In other words you can say that
each object of a class has its own copy of data members defined in
the class.
•Member functions have only one copy and shared by all the
objects of that class.
•All objects may have their own value of variables.
•The new Operator is used to create an object.
•Syntax : $object_name=new class_name;
Creating Object
class Mobile
{
public $model;
function showModel($number)
{
$this->model=$number;
echo “Model Number: $this->model”;
}
}
$samsung=new Mobile;
Accessing class member using
object:
•-> operator is used to access class member using
object.
•Syntax :
object_name->variable_name;
object_name->method_name();
Example:
$samsung->model;
$samsung->showModel();
Constructor
•PHP supports a special type of method called
constructor for initializing an object when it is created.
This is known as automatic initializing of objects.
•A class constructor if define is called whenever a
program creates an object of that class.
•They are invoked directly when an object is created.
•A constructor should have the same name as the class.
•Constructor have a special name in PHP __construct
Example:
<?php
class Student
{
function __construct()
{
echo “Constructor Called”;
}
}
$stud=new Student;
?>
Type of Constructor :

•Default Constructor
•Parameterized Constructor
Default Constructor
•A default constructor is a constructor that has
no parameters.
•Example:
class Student
{
function __construct()
{
echo “Default constructor”;
}
}
$stud=new Student;
Parameterized Constructor
•The constructor that can take the arguments are called parameterized
constructors.
•Example:
class Student
{
public $roll;
function __construct($enroll)
{
$this->roll=$enroll;
echo $this->roll;
}
}
$stud=new Student(10);

Note: Once you create your own constructor, the default constructor is
no longer accessible.
Destructors
•In PHP destructor are called when you explicitly
destroy an object or when all references to the
object go out of scope.
•Destructor have a special name in PHP __destruct.
•Destructor do not have any arguments.
•Syntax :
function __destruct()
{
echo “Destroyed”;
}
Example:
<?php
class Student
{
public $roll;
function __construct($enroll)
{
$this->roll=$enroll;
echo $this->roll;
}
function __destruct()
{
echo “<br>object trashed”;
}
}
$stud=new Student(10);
?>

Output :
10
object trashed
Inheritance:
●The mechanism of deriving a new class from an old
one is called inheritance or derivation.

Old Class

New Class
Super Class and Sub Class:
−The old class is referred to as the Super class and
the new one is called the Sub class.
●Parent class : Base class or super class
●Child Class : Derived class, Extended class or sub
class.
Type of Inheritance :

●Single Inheritance
●Multiple Inheritance
●Multi-level Inheritance
●Hierarchical Inheritance
Single Inheritance
If a class is derived from one base class (Parent
Class), it is called Single Inheritance.
Syntax :
class parent_class_name
{
members of class
}
class child_class_name extends Parent_class_name
{
members of class
}
Example:
<?php
class father
{
public $a,$b;
function getvalue($x,$y){
$this->a=$x;
$this->b=$y;
}
}
class son extends father
{
function display(){
echo “Value of A: $this->a <br>”;
echo “Value of B: $this->b <br>”;
}
}
$obj=new son;
$obj->getvalue(10,20);
$obj->display();
?>
Multi-level Inheritance :

In multi-level inheritance, the class inherits the feature of


another derived class.

Father

Son

GrandSon
Syntax :
class father
{
Members of class
}
class son extends father
{
Members of class
}
class grandson extends son
{
Members of class
}
Multiple Inheritance :

If a class is derived from more than one parent class,


then it is called multiple inheritance.
PHP does not allow multiple inheritance. So traits is
used to fulfill this gap by allowing us to reuse functionality
in Multiple classes.
A B

C
Example :
class C extends A
<?php {
class A use B;
{ function disp2()
function disp() {
{ echo “Child-C”;
echo “Parent-A”; }
} }
} $obj=new C();
trait B $obj->disp();
{ $obj->disp1();
function disp1() $obj->disp2();
{ ?>
echo “Parent-B”;
}
}
Output:
Parent-A
Parent-B
Child-C
Hierarchical Inheritance

Father

Son Daughter Son

Child
Method Overloading :

• If the derived class is having the same name method


name as base class then the method in the derived class
takes precedence over or overrides the base class
method.
• Function overloading or method overloading is the ability
to create multiple functions of the same name with different
implementations depending on the types of their arguments.
Method Overloading: It is a type of overloading for
creating dynamic methods that are not declared within the
class scope. PHP method overloading also triggers magic
methods dedicated to the appropriate purpose. Unlike
property overloading, PHP method overloading allows
function call on both object and static context. The related
magic functions are,

● __call() – triggered while invoking overloaded


methods in the object context.
● __callStatic() – triggered while invoking overloaded
methods in static context.
Example :
<?php
class GFG {

public function __call($name, $arguments) {

echo "Calling object method '$name' "


. implode(', ', $arguments). "\n";
}

public static function __callStatic($name, $arguments) {

echo "Calling static method '$name' "


. implode(', ', $arguments). "\n";
}
}

// Create new object Output :


Calling object method 'runTest' in object context
$obj = new GFG;
Calling static method 'runTest' in static context

$obj->runTest('in object context');

GFG::runTest('in static context');

?>
Method overriding :

Overriding refer to the ability of a subclass to re-implement


a method inherited from a superclass.

• Only inherited method can be overridden.


• Final and static method can not be overridden.
• The overriding method must have same argument list.
Example:
<?php
class father
{
function disp(){echo “super class”;}
}
class son extends father
{
function disp(){echo “son class”;}
}
$obj= new father;
$obj->disp();
$obj1= new son;
$obj1->disp();
?>
Object Cloning

Object cloning means creating copy of object.


If we perform $s2=$s1 then it is called shallow copy.
If we perform $s2=clone $s1 then it is called deep copy.

$s1 $s2 $s1 $s2

Name:”ABC” Name:”ABC” Name:”ABC”


Rollno=101 Rollno=101 Rollno=101

This is shallow copy This is deep


copy
<?php
class student
{
private $name;
private $rollno;

function __construct($name,$rollno)
{
$this->name=$name;
$this->rollno=$rollno;
}
/*function __clone()
{
echo "<h3>Copying object.....</h3>";
}
*/
function display()
{
echo"<h4> Name:$this->name</h4>";
echo"<h4> RollNo:$this->rollno</h4>";
}}
$s1=new student("Ashwini",101);
$s2=new student("Sharda",102);
$s1->display();
//$s2=clone $s1;
$s2->display();
?>

Output :without __clone()


Name:Ashwini
RollNo:101
Name:Sharda
RollNo:102

Output : with __clone()


Name:Ashwini
RollNo:101
Copying object.....
Name:Ashwini
RollNo:101
PHP Introspection

Introspection is the ability of a program to examine an objects characteristics,


Such as its name, parent class, properties and method.

class_exists() – checks whether a class has been defined


Syntax : $yes_no= class_exists(class_name)

get_class() – returns the class name of an object


Syntax : $classname=get_class(class_name)

get_parent_class() – returns the class name of an object’s parent class


Syntax : $superclass=get_parent_class(class_name)

is_subclass_of() – checks whether an object has a given parent class


Syntax : is_subclass_of($object, $class_name );

get_class_methods()- returns an array of class methods name.


Syntax : $method=get_class_methods(class_name);
Example :

<?php
class parent1
{
public function myfun()
{
echo “<br>***** In parent class ****”;
echo “<br>This function is inside:”.get_class($this);
}
}
class child extends parent1
{
public function myfun()
{
echo “<br>***** In child class ****”;
echo “<br>This function is inside:”.get_class($this);
echo “<br>This parent of this class is:”.get_parent_class($this);
}
}
if(class_exists(“parent1”))
{
$obj_p1=new parent1();
echo “<br> the class name is :”.get_class($obj_p1);
$obj_p1->myfun();
}
if(class_exists(“child”))
{
$obj_c=new child();
echo “<br> the class name is :”.get_class($obj_c);
$obj_c->myfun();
}
?>

Output :
the class name is :parent1
***** In parent class ****
This function is inside:parent1

the class name is :child


***** In child class ****
This function is inside:child
This parent of this class is:parent1
Serializing objects

serialize() returns a string containing a byte-stream representation of


any value that can be stored in PHP.
It is useful for storing or passing PHP values around without losing their type and
structure.

unserialize() can use this string to recreate the original variable values.
Example :
<?php
$a=array("a"=>"Rupali","b"=>"Sonali");
print "Serialize array";
$str=serialize($a);
print $str;
echo "<br>";
print "Unserialize array";
$arr=unserialize($str);
print_r($arr);
?>

Output :
Serialize arraya:2:{s:1:"a";s:6:"Rupali";s:1:"b";s:6:"Sonali";}
Unserialize arrayArray(
[a] => Rupali
[b] => Sonali
)

You might also like