PHP CH 03 52859676 2025 02 04 10 48
PHP CH 03 52859676 2025 02 04 10 48
Syntax
<?php
class ClassName
{
//...
}
?>
Example:
Below we declare a class named Fruit consisting of two properties ($name and $color) and two
methods set_data() and get_data() for setting and getting the property:
class Fruit
{
public $name;
public $color;
function set_data($name,$color)
{
$this->name = $name;
$this->color = $color;
}
function get_data()
{
echo "Name of Fruit is ", $this->name,"<br>";
echo "Color of Fruit is ", $this->color;
}
}
Note: In a class, variables are called properties and functions are called methods!
`
Define Objects
We can create multiple objects from a class.
Each object has all the properties and methods defined in the class, but they will have different
property values.
Object of a class is created using the new keyword.
Example:
$apple = new Fruit();
$mango = new Fruit();
The object operator i.e. arrow symbol (->) is an OOP construct that is used to access properties and
methods for a given object.
$object->property;
$object->method( );
Example
<?php
class Fruit
{
public $name;
public $color;
function set_data($name,$color)
{
$this->name = $name;
$this->color = $color;
}
function get_data()
{
echo "Name of Fruit is ", $this->name,"<br>";
echo "Color of Fruit is ", $this->color;
}
}
The $this keyword refers to the current object, and is only available inside methods.
The $this keyword allows you to access the properties and methods of the current object within
the class using the object operator (->):
$this->property
$this->method()
It doesn’t exist outside of the class. If you attempt to use the $this outside of a class, you’ll get an
error.
When you access an object property using the $this keyword, you use the $ with the this keyword only.
And you don’t use the $ with the property name.
Example
<?php
class Fruit {
public $name;
public $color;
function set_data($name,$color)
{
$this->name = $name;
$this->color = $color;
}
function get_data()
{
echo "Name of Fruit is ", $this->name,"<br>";
echo "Color of Fruit is ", $this->color;
}
}
Output:
Name of Fruit is Apple
Color of Fruit is Red
`
Change the property value directly Outside the class:
Example
<?php
class Fruit
{
public $name;
public $color;
function get_data()
{
echo "Name of Fruit is ", $this->name,"<br>";
echo "Color of Fruit is ", $this->color;
}
}
function get_data($length,$breadth)
{
$this->length=$length;
$this->breadth=$breadth;
}
function perimeter()
{
$this->p= 2*($this->length + $this->breadth);
echo "Perimeter is ", $this->p,"<br>";
}
function area()
{
$this-> a = $this->length * $this->breadth;
echo "Area is ", $this->a;
}
}
Output:-
Perimeter is 60
Area is 200
`
Program : Calculate Area and Circumference of Circle
<?php
class Circle
{
public $radius;
function set_data($radius)
{
$this->radius=$radius;
}
function area()
{
echo "Area of circle is ". (3.14 * $this->radius*$this->radius)."<br>";
}
function circumference()
{
echo "circumference of Circle is ".(2*3.14*$this->radius);
}
}
$obj = new Circle();
$obj->set_data(5);
$obj->area();
$obj->circumference();
?>
<?php
class Circle
{
public $radius;
function set_data($radius)
{
$this->radius=$radius;
}
function area()
{
$a = 3.14*$this->radius*$this->radius; // $a does not require this keyword
`
return $a;
}
function circumference()
{
$c = 2*3.14*$this->radius;
return $c;
}
}
$obj = new Circle();
$obj->set_data(10);
echo "Area of Circle is ",$obj->area();
echo "Circumference of Circle is ",$obj->circumference();
?>
PHP - instanceof
You can use the instanceof keyword to check if an object belongs to a specific class:
Example:-
var_dump($apple instanceof Fruit);
Constructor
The __construct Function
Constructor are special type of functions which are called automatically whenever an object is
created.
A constructor allows you to initialize an object's properties upon creation of the object.
PHP provides a special function called __construct() to define a constructor.
You can pass as many as arguments you like into the constructor function.
Notice that the construct function starts with two underscores (_ _)!
class ClassName
{
function __construct()
{
// implementation
}
}
When you create an instance of the class, PHP automatically calls the constructor method:
Example
<?php
class Fruit
{
public $name;
function __construct($name)
{
$this->name = $name;
}
function get_name()
{
return $this->name;
}
}
Example
<?php
class Fruit {
public $name;
public $color;
{
$this->name = $name;
`
$this->color = $color;
}
function get_name()
{
return $this->name;
}
function get_color()
{
return $this->color;
}
}
$apple = new Fruit("Apple", "red");
echo $apple->get_name();
echo "<br>";
echo $apple->get_color();
?>
Destructor
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.
Notice that the destruct function starts with two underscores (_ _)!
function __destruct()
Example
<?php
class Fruit
{
public $name;
public $color;
function __construct($name,$color)
{
$this->name= $name;
$this->color= $color;
}
`
function get_name()
{
echo "Name of Fruit is ". $this->name."<br>";
}
function get_color()
{
echo "Color of Fruit is ".$this->color."<br>";
}
function __destruct()
{
echo "Object is Destroyed";
}
?>
2) Parameterized Constructor
A constructor can be with or without arguments. The constructor with arguments is called the
parameterized constructor
<?php
class Person
{
public $first;
public $email;
public $mobile;
Output:
Initialising the object...
My name is: Akshay
Email_Id is [email protected]
Mobile Number is 8788335443
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
In the following example we have added three different access modifiers to the three properties. Here,
if you try to set the name property it will work fine (because the name property is public). However, if
you try to set the color or weight property it will result in a fatal error (because the color and weight
property are protected and private):
Example
<?php
class Fruit
{
public $name;
protected $color;
private $weight;
}
In the next example we have added access modifiers to two methods. Here, if you try to call the
set_color() or the set_weight() function it will result in a fatal error (because the two functions are
considered protected and private), even if all the properties are public:
Example
<?php
class Fruit
{
public $name;
public $color;
public $weight;
function set_name($n)
{ // a protected function
$this->color = $n;
}
private function set_weight($n)
{ // a private function
$this->weight = $n;
}
}
Output
Fatal error: Uncaught Error: Call to protected method Fruit::set_color() from global scope in
C:\xampp\htdocs\PHP_PROGRAM\access.php:20 Stack trace: #0 {main} thrown
in C:\xampp\htdocs\PHP_PROGRAM\access.php on line 20
`
PHP - What is Inheritance?
Inheritance is the way of extending the existing class functionality in the newly created class.
We can also add some additional functionality to the newly created class apart from extending the base
class functionalities.
When we inherit one class, we say an inherited class is a child class (sub class) and from which we
inherit is called the parent class. The parent class is also known as the base class.
This is the way that enables the better management of the programming code and code reusability.
The child class will inherit all the public and protected properties and methods from the parent
class.
In addition, it can have its own properties and methods.
An inherited class is defined by using the extends keyword.
Single Inheritance: PHP supports Single inheritance. Single inheritance is a concept in PHP in which
one class can be inherited by a single class only. We need to have two classes in between this process.
One is the base class (parent class), and the other a child class itself.
Hierarchical Inheritance: As the name suggests, the hierarchical inheritance adopts a tree-like
structure, where multiple derived classes are inherited from the base class.
Multilevel Inheritance: Multilevel inheritance is the third type of inheritance supported in PHP. It
occurs at different levels. Here, one base class is inherited by a derived class, then that derived class
is inherited by other derived classes, and so on.
Output:-
Am I a fruit
The fruit is Apple
the color is Red
Example
<?php
class Fruit
{
public $name;
public $color;
public function __construct($name, $color)
{
$this->name = $name;
$this->color = $color;
}
protected function display()
{
echo "The fruit is ". $this->name."<br>";
echo "the color is ". $this->color;
}
}
class Apple extends Fruit
{
function message()
{
echo "Am I a fruit "."<br>";
}
}
$s = new Apple("Apple", "Red"); // OK. __construct() is public
$s->message();// OK. message() is public
$s->display(); // ERROR. display() is protected
?>
`
In the example above we see that if we try to call a protected method (display()) from outside the class,
we will receive an error. public methods will work fine!
Let's look at another example: Here we will call the protected method (display ()) from inside the
derived class.
Example
<?php
class Fruit
{
public $name;
public $color;
public function __construct($name, $color)
{
$this->name = $name;
$this->color = $color;
}
protected function display()
{
echo "The fruit is ". $this->name."<br>";
echo "the color is ". $this->color;
}
}
class Apple extends Fruit
{
function message()
{
echo "Am I a fruit "."<br>";
$this->display();
}
}
$s = new Apple("Apple", "Red"); // OK. __construct() is public
$s->message(); // OK. message() is public and it calls intro() (which is protected) from within the
derived class
?>
Output:-
Am I a fruit
The fruit is Apple
the color is Red
`
Multi-level inheritance
Example:-
<?php
//PHP program to demonstrate the multi-level inheritance.
class Base
{
function BaseFun()
{
echo "BaseFun() called <br>";
}
}
?>
Hierarchical inheritance
<?php
//PHP program to demonstrate the hierarchical inheritance.
class Base
{
function BaseFun()
{
echo "BaseFun() called<br>";
}
}
`
class Derived1 extends Base
{
function Derived1Fun()
{
echo "Derived1Fun() called<br>";
}
}
$Obj1->BaseFun();
$Obj1->Derived1Fun();
echo "<br>";
$Obj2->BaseFun();
$Obj2->Derived2Fun();
?>
Multiple Inheritance
Multiple Inheritance is the property of the Object Oriented Programming languages in which child
class or sub class can inherit the properties of the multiple parent classes or super classes.
PHP doesn’t support multiple inheritance but by using Interfaces in PHP or using trait in PHP
instead of classes, we can implement it.
Traits are used to declare methods that can be used in multiple classes. Traits can have methods and
abstract methods that can be used in multiple classes, and the methods can have any access modifier
(public, private, or protected).
Traits are declared with the trait keyword:
Syntax
<?php
trait TraitName
{
// some code...
}
?>
`
To use a trait in a class, use the use keyword:
Syntax
<?php
class child_class extends parent_class
{
use trait_name;
..
..
Child_class function/functions
}
?>
Example:-
<?php
class A // Parent Class
{
function display1()
{
echo "Hello ";
}
}
trait B // Trait
{
function display2()
{
`
echo "Welcome ";
}
}
function display3()
{
echo "Arrow Academy ";
}
}
Interfaces
An interface consists of methods that have no implementations, which means the interface
methods are abstract methods.
Any classes implementing an interface must implement all methods defined by the
interface.
All the methods in interfaces must have public visibility scope.
Interfaces are different from classes as the class can inherit from one class only whereas the
class can implement one or more interfaces
A class can implement multiple interfaces.
An interface is declared using the "interface" keyword.
// defines the interface methods and may have its own code
}
`
Example:-
<?php
class A // Parent Class
{
function display1()
{
echo "You are in Class A <br>";
}
}
function display3()
{
echo "You are in Class C ";
}
}
interface C
{
public function display3();
}
An abstract class is a class that contains at least one abstract method. An abstract method is a
method that is declared, but not implemented in the code.
An abstract class or method is defined with the abstract keyword.
Classes defined as abstract cannot be instantiated.
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration
must be defined by the child class
Syntax:-
abstract class class_name
{
abstract public function method_name( $param1, $param2 );
}
Example:-
<?php
// Abstract class
abstract class Base
{
// This is abstract function
abstract function printdata();
}
class Derived extends Base
{
function printdata()
{
echo "Derived class";
}
}
$b1 = new Derived;
$b1->printdata();
?>
`
Concrete Class:
The class which implements an interface is called the Concrete Class.
It must implement all the methods defined in an interface.
<?php
interface MyInterfaceName
{
?>
Output:
Method1 Called
Method2 Called
`
Property Overloading
PHP property overloading is used to create dynamic properties when the object is set.
For creating these properties no separate line of code is needed.
A property associated with a class instance, and if it is not declared within the scope of the class, it is
considered as overloaded property.
To achieve this we can use the magic method
__set(): triggered while initializing overloaded properties.
__get(): triggered while using overloaded properties with PHP print statements.
__isset(): This magic method is invoked when we check overloaded properties with isset() function
__unset(): Similarly, this function will be invoked on using PHP unset() for overloaded properties.
Program:-
<?php
class myclass
{
function __set($name,$value)
{
echo "Setting $name propert with $value <br>";
$this->$name=$value;
}
function __get($name)
{
return $this->name;
}
function __isset($name)
{
return isset($this->name);
}
function __unset($name)
{
unset($this->name);
}
}
$obj = new myclass();
$obj->myprop="test"; // Invoke set()
echo "Value of overloaded Property is ";
echo $obj->myprop; // Invoke get()
echo "<br>";
var_dump (isset($obj->myprop));
unset($obj->myprop);
echo "<br>";
var_dump(isset($obj->myprop));
?>Output:-
Setting myprop propert with test
Value of overloaded Property is test
bool(true)
bool(false)
`
Function Overloading:
Function overloading contains same function name and that function performs different task
according to number of arguments. For example, find the area of certain shapes where radius are given
then it should return area of circle, if height and width are given then it should give area of rectangle
and others. Like other OOP languages function overloading can not be done by native approach. In PHP
function overloading is done with the help of magic function __call(). This function takes function name
and arguments.
Syntax:
public __call (string $name1 , array $arguments1 )
Example:-
<?php
// PHP program to explain function
// overloading in PHP
switch (count($arguments)) {
class Calculate
{
function __call($name, $arguments)
{
if($name == 'add')
{
switch (count($arguments))
{
case 1:
return $arguments[0];
case 2:
return $arguments[0] + $arguments[1];
case 3:
return $arguments[0] + $arguments[1] + $arguments[2];
case 4:
return $arguments[0] + $arguments[1] + $arguments[2] + $arguments[3];
}
}
}
}
}
class Derived extends Base {
function display() {
echo " Derived class function!";
}
}
$ob = new Derived;
$ob->display();
?>
Example 2:
Look at the example below. The __construct() and intro() methods in the child class (Strawberry) will
override the __construct() and intro() methods in the parent class (Fruit):
<?php
class Fruit
{
public $name;
public $color;
function __construct($name,$color)
{
$this->name= $name;
$this->color = $color;
}
function display()
{
echo "Name is ".$this->name;
echo "Color is ".$this->color;
}
`
}
function __construct($name,$color,$weight)
{
$this->name= $name;
$this->color = $color;
$this->weight = $weight;
}
function display()
{
echo "Name is ".$this->name."<br>";
echo "Color is ".$this->color."<br>";
echo "Weight is ".$this->weight."<br>";
}
}
?>
Output:
Name is Apple
Color is Red
Weight is 100
`
final Keyword
The final keyword can be used to prevent class inheritance or to prevent method overriding.
When a class is declared as Final , it can not be Inherited.
When a method is declared as Final , then overriding can not be performed on that method..
Output:-
Fatal error: Class Derived may not inherit from final class (Base)
in C:\xampp\htdocs\Practicals\Demo.php on line 11
<?php
class Base {
final function display() {
echo "Base class function ";
}
}
class Derived extends Base {
function display() {
echo " Derived class function!";
}
}
$ob = new Derived;
$ob->display();
?>
`
Output:-
Example:-
<?php
class myclass
{
public $name;
public $city;
function __construct($name,$city)
{
$this->name= $name;
$this->city=$city;
}
}
$obj2->name= "Akshay";
`
$obj2->city= "Pune";
echo "<br>";
echo "After Changing Properties <br>";
echo "Original Object <br>";
print_r($obj1);
echo "<br>";
?>
Output:-
Original Object
myclass Object ( [name] => Arrow [city] => Ahmednagar )
Duplicate Object
myclass Object ( [name] => Arrow [city] => Ahmednagar )
After Changing Properties
Original Object
myclass Object ( [name] => Akshay [city] => Pune )
Duplicate Object
myclass Object ( [name] => Akshay [city] => Pune )
<?php
class myclass
{
public $name;
public $city;
function __construct($name,$city)
{
$this->name= $name;
$this->city=$city;
}
}
$obj2->name= "Akshay";
$obj2->city= "Pune";
echo "<br>";
echo "After Changing Properties <br>";
echo "Original Object <br>";
print_r($obj1);
echo "<br>";
?>
Output:
Original Object
myclass Object ( [name] => Arrow [city] => Ahmednagar )
Duplicate Object
myclass Object ( [name] => Arrow [city] => Ahmednagar )
After Changing Properties
Original Object
myclass Object ( [name] => Arrow [city] => Ahmednagar )
Duplicate Object
myclass Object ( [name] => Akshay [city] => Pune )
`
Shallow Copy vs Deep Copy
Shallow Copy
As mentioned ealier, the clone performs a shallow copy of an object. It means that:
1. Create a copy of all properties of an object.
2. If a property references another object, the property remains a reference.
In other words, when an object has a property that references another object, that property remains a
reference after cloning.
<?php
class address
{
public $city = "Nanded";
public $pin = "123456";
function setaddr($city,$pin)
{
$this->city= $city;
$this->pin=$pin;
}
}
class myclass
{
public $name = "Raja";
public $obj;
function setname($name)
{
$this->name= $name;
}
}
$obj2=clone $obj1;
$obj2->setname("Akshay");
`
$obj2->obj->setaddr("Nagar","414001");
echo "<br>";
echo "Original Object <br>";
print_r ($obj1);
echo "<br>";
echo "Duplicate Object <br>";
print_r ($obj2);
?>
Output:-
Original Object
myclass Object ( [name] => Raja [obj] => address Object ( [city] => Nanded [pin] => 123456 ) )
Duplicate Object
myclass Object ( [name] => Raja [obj] => address Object ( [city] => Nanded [pin] => 123456 ) )
Original Object
myclass Object ( [name] => Raja [obj] => address Object ( [city] => Nagar [pin] => 414001 ) )
Duplicate Object
myclass Object ( [name] => Akshay [obj] => address Object ( [city] => Nagar [pin] => 414001 ) )
`
Deep copy with __clone method
Deep copy creates a copy of an object and recursively creates a copy of the objects referenced by the
properties of the object.
The __clone() method creates a deep copy by creating clone of embedded object too.
Example:-
<?php
class address
{
public $city = "Nanded";
public $pin = "123456";
function setaddr($city,$pin)
{
$this->city= $city;
$this->pin=$pin;
}
}
class myclass
{
public $name = "Raja";
public $obj;
function setname($name)
{
$this->name= $name;
}
function __clone()
{
$this->obj= clone $this->obj;
}
}
$obj2=clone $obj1;
$obj2->setname("Akshay");
$obj2->obj->setaddr("Nagar","414001");
echo "<br>";
echo "Original Object <br>";
print_r ($obj1);
echo "<br>";
echo "Duplicate Object <br>";
print_r ($obj2);
?>
Output:-
Original Object
myclass Object ( [name] => Raja [obj] => address Object ( [city] => Nanded [pin] => 123456 ) )
Duplicate Object
myclass Object ( [name] => Raja [obj] => address Object ( [city] => Nanded [pin] => 123456 ) )
Original Object
myclass Object ( [name] => Raja [obj] => address Object ( [city] => Nanded [pin] => 123456 ) )
Duplicate Object
myclass Object ( [name] => Akshay [obj] => address Object ( [city] => Nagar [pin] => 414001 ) )
`
Introspection in PHP:
Introspection is the ability of a program to examine an object's characteristics, such as its name, parent
class (if any), properties, and methods.
PHP offers a large number of functions that you can use to accomplish the task.
The following are the functions to extract basic information about classes such as their name, the name
of their parent class and so on.
In-built functions in PHP Introspection :
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 object's parent class.
is_subclass_of() Checks whether an object has a given parent class.
get_declared_classes() Returns a list of all declared classes.
get_class_methods() Returns the names of the class methods.
get_class_vars() Returns the default properties of a class
interface_exists() Checks whether the interface is defined.
method_exists() Checks whether an object defines a method.
To determine whether a class exists, use the class_exists( ) function, which takes in a string and
returns a Boolean value.
Example 1: class_exists( )
<?php
if(class_exists('arrow'))
{
$ob=new arrow();
echo "This is Arrow Computer";
}
else
{
echo "Not exist";
}
?>
Output: Not exist
`
Example 2: class_exists( )
<?php
class arrow
{
//Body
}
if(class_exists('arrow'))
{
$ob=new arrow();
echo "This is Arrow";
}
else
{
echo "Not exist";
}
?>
Output: This is Arrow
`
The get_class() and get_parent_class() methods return the class name of an object or its parent’s
class name respectively. Both takes as arguments an object instance.
The is_subclass_of() methods takes an object instance as its first argument and a string, representing
the parent class name, Checks whether an object has a given parent class.
Example 3:
<?php
class A
{
public function description()
{
echo "I am a super class for the Child class <br>";
}
}
class B extends A
{
public function description()
{
echo "I am Class " .get_class($this)."<br>";
echo "I am Child Class of " .get_parent_class($this)."<br>";
}
}
if (class_exists('A'))
{
$base = new A();
echo "The class name is: " . get_class($base)."<br>";
$base->description();
}
if (class_exists('B'))
{
$child = new B();
$child->description();
if (is_subclass_of($child,'A'))
{
echo "Yes, " . get_class($child) . " is a subclass of A";
}
else
{
echo "No, " . get_class($child) . " is not a subclass of A";
}
}
`
The output of the above code should be as follows:
if(interface_exists('Test'))
{
echo "Interface Test Exists <br>";
}
else
{
echo "Interface Test Does Not Exists";
}
$t = new Myclass();
$t->display1();
Output:-
Interface Test Exists
Dipslay 1 method From Interface Test
You can get the methods and properties that exist in a class (including those that are inherited from
superclasses) using the get_class_methods( ) and get_class_vars( ) functions. These functions take a
class name and return an array:
`
Example 6:
<?php
class Rectangle
{
var $length = 2;
var $breadth = 10;
function get($length,$breadth)
{
$this->length = $length;
$this->breadth = $breadth;
}
function area()
{
return $this->length*$this->breadth;
}
function display()
{
// any code to display info
}
}
$S = new Rectangle();
$S->get(4,2);
//get the class varibale i.e properties
$class_properties = get_class_vars('Rectangle');
print_r($class_properties);
echo "<br>";
print_r($class_methods);
echo "<br>";
print_r($object_class);
?>
Output:
Array ( [length] => 2 [breadth] => 10 )
Array ( [0] => Rectangle [1] => area [2] => display )
Rectangle
`
1. Serialize
The serialize() is an inbuilt function PHP that is used to serialize the given array.
The serialize() function converts a storable representation of a value.
To serialize data means to convert a value to a sequence of bits, so that it can be stored in a file, a
memory buffer, or transmitted across a network.
The serialize() function accepts a single parameter which is the data we want to serialize and returns a
serialized string.
Syntax
serialize($values_in_form_of_array);
Example 1:
<?php
// Complex array
$arr = array("Red", "Green", "Blue");
?>
Output:
a:3:{i:0;s:3:"Red";i:1;s:5:"Green";i:2;s:4:"Blue";}
Example 2:
<?php
class test1
{
private $name;
function __construct($arg)
{
$this->name=$arg;
}
}
$obj1=new test1("Akshay");
$str=serialize($obj1);
echo $str
?>
Output:
The unserialize() function converts serialized data back into actual data.
Syntax:-
Unserialize( $serialized_array )
Example
Convert serialized data back into actual data:
<?php
$arr = array("Red", "Green", "Blue");
$data = serialize($arr);
echo $data . "<br>";
$test = unserialize($data);
var_dump($test);
?>
Output:
a:3:{i:0;s:3:"Red";i:1;s:5:"Green";i:2;s:4:"Blue";}
array(3) { [0]=> string(3) "Red" [1]=> string(5) "Green" [2]=> string(4) "Blue" }