0% found this document useful (0 votes)
16 views46 pages

Attachment

This document discusses Object-Oriented Programming (OOP) concepts in PHP, emphasizing the importance of classes and objects, encapsulation, and the benefits of reusability, modularity, flexibility, and maintainability. It explains key components such as access modifiers, the $this keyword, constructors, and destructors, along with examples of defining classes and creating objects. The document also touches on inheritance and copy constructors, highlighting how they contribute to effective software development in PHP.

Uploaded by

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

Attachment

This document discusses Object-Oriented Programming (OOP) concepts in PHP, emphasizing the importance of classes and objects, encapsulation, and the benefits of reusability, modularity, flexibility, and maintainability. It explains key components such as access modifiers, the $this keyword, constructors, and destructors, along with examples of defining classes and creating objects. The document also touches on inheritance and copy constructors, highlighting how they contribute to effective software development in PHP.

Uploaded by

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

Web Based Application Development with

PHP
Day 3.1:

Chapter 3: Apply Object Oriented Concepts in PHP

We can imagine our universe made of different objects like sun, earth, moon etc.
Similarly we can imagine our car made of different objects like wheel, steering, gear etc.
Same way there is object oriented programming concepts which assume everything as
an object and implement a software using different objects.

What is OOPS?
Object-Oriented Programming or simply OOPs is a programming approach or paradigm
that gives its prime consideration to the data and its associated functions. It uses the
concept of wrapping up the data as an object-entity having its associated properties, to
provide higher security and less exposure to the data. As nothing is more important than
the data itself, this approach is highly in use and widely accepted by programmers
worldwide. The programming languages that do not support OOPs methodologies and
their concepts are slowly getting deprecated, and the languages that are now being
developed, support OOPs and are the extended version of object-oriented
programming.

To relate programming with the real world, this methodology considers everything in the
world as an entity or an object, and every object has some of its attributes or properties.
So, the concept of the classes and objects can be applied to model an entire
application. The overall development of an application in an object-oriented perspective
can be summarized as:

●​ The object-oriented analysis describes the application’s functionality.


●​ The application’s architecture is described by designing it using an
object-oriented approach.
●​ The application’s implementation is described by programming it using the
object-oriented method.
What are the Benefits of OOP in PHP?

Object-oriented programming (OOP) is a popular programming paradigm that is widely


used in PHP. This approach allows developers to break down their code into smaller,
reusable components called objects. Let’s check out a few benefits of OOP in PHP.

Reusability
OOP allows you to create reusable code by encapsulating functionality within classes.
Once a class is defined, you can create multiple instances (objects) of that class,
making it easy to reuse the code across different parts of your application. Code reuse
not only saves development time but also enhances consistency and reduces the
likelihood of errors.

Modularity
OOP promotes a modular approach to software development. You can break down your
application into smaller, manageable modules or classes. Each class represents a
specific entity or functionality, making it easier to understand, maintain, and update.

Modules can be developed independently, which facilitates collaborative development


and allows for easy integration and testing.

Flexibility
OOP provides flexibility in design and implementation. With features like inheritance and
polymorphism, you can create a hierarchy of classes, allowing for the extension and
modification of existing code without altering its core functionality.

Polymorphism, in particular, enables you to use a common interface to represent


different types of objects, making it easier to adapt your code to changing requirements.

Maintainability
OOP promotes code organization and structure, making it easier to understand and
maintain. Classes encapsulate data and behavior, providing a clear separation of
concerns.

Changes to one part of the codebase are less likely to affect other parts if the code is
well-designed using OOP principles. This isolation makes it easier to debug, update,
and enhance the application over time.
Define a 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 Fruit {​
// code goes here...​
}​
?>

Below we declare a class named Fruit consisting of two properties ($name and $color)
and two methods set_name() and get_name() for setting and getting the $name
property:

<?php​
class Fruit {​
// Properties​
public $name;​
public $color;​

// Methods​
function set_name($name) {​
$this->name = $name;​
}​
function get_name() {​
return $this->name;​
}​
}​
?>

Note: In a class, variables are called properties and functions are called methods!

Define Objects
Classes are nothing without 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.

Objects of a class are created using the new keyword.


In the example below, $apple and $banana are instances of the class Fruit:
Example:​

<?php​
class Fruit {​
// Properties​
public $name;​
public $color;​

// Methods​
function set_name($name) {​
$this->name = $name;​
}​
function get_name() {​
return $this->name;​
}​
}​

$apple = new Fruit();​
$banana = new Fruit();​
$apple->set_name('Apple');​
$banana->set_name('Banana');​

echo $apple->get_name();​
echo "<br>";​
echo $banana->get_name();​
?>

In the example below, we add two more methods to class Fruit, for setting and getting
the $color property:

Example:​

<?php​
class Fruit {​
// Properties​
public $name;​
public $color;​

// Methods​
function set_name($name) {​
$this->name = $name;​
}​
function get_name() {​
return $this->name;​
}​
function set_color($color) {​
$this->color = $color;​
}​
function get_color() {​
return $this->color;​
}​
}​

$apple = new Fruit();​
$apple->set_name('Apple');​
$apple->set_color('Red');​
echo "Name: " . $apple->get_name();​
echo "<br>";​
echo "Color: " . $apple->get_color();​
?>

<?php

class Fruits
{
public $name; // Data members or variable
public $color; // Data members or variable

public function setName($text1) // Member function definition


{
$this->name = $text1;
}
public function getName() // Member function definition
{
return $this->name;
}

public function setColor($text2)


{
$this->color = $text2;
}

public function getColor()


{
return $this->color;
}

$f1 = new Fruits();

$f1->setName("Apple");

$f1->setColor("Red");

$val = $f1->getName();
echo $val;

echo $f1->getColor();

$f2 = new Fruits();


$f2->setName("Orange");
$f2->setColor("Orange");

print $f2->getName();
print $f2->getColor();

?>
Web Based Application Development with
PHP
Day 3.2:

Chapter 3: Apply Object Oriented Concepts in PHP

PHP - The $this Keyword

The $this keyword refers to the current object, and is only available inside methods.

Look at the following example:

Example:​
<?php​
class Fruit {​
public $name;​
}​
$apple = new Fruit();​
?>

So, where can we change the value of the $name property? There are two ways:

1. Inside the class (by adding a set_name() method and use $this):
Example:​
<?php​
class Fruit {​
private $name;​
function set_name($name) {​
$this->name = $name;​
}​
}​
$apple = new Fruit();​
$apple->set_name("Apple");​

echo $apple->name;​
?>

2. Outside the class (by directly changing the property value):

Example:​
<?php​
class Fruit {​
public $name;​
}​
$apple = new Fruit();​
$apple->name = "Apple";​

echo $apple->name;​
?>

PHP - Access Modifiers

Properties and methods can have access modifiers which control where they can be
accessed.

There are three access modifiers:


●​ 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 three
properties (name, color, and weight). Here, if you try to set the name property it will work
fine (because the name property is public, and can be accessed from everywhere).
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;​
}​

$mango = new Fruit();​
$mango->name = 'Mango'; // OK​
$mango->color = 'Yellow'; // ERROR​
$mango->weight = '300'; // ERROR​
?>

In the next example we have added access modifiers to two functions. 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:

<?php​
class Fruit {​
public $name;​
public $color;​
public $weight;​

function set_name($n) { // a public function (default)​
$this->name = $n;​
}​
protected function set_color($n) { // a protected function​
$this->color = $n;​
}​
private function set_weight($n) { // a private function​
$this->weight = $n;​
}​
}​

$mango = new Fruit();​
$mango->set_name('Mango'); // OK​
$mango->set_color('Yellow'); // ERROR​
$mango->set_weight('300'); // ERROR​
?>
Difference between self and $this:

The keyword self is used to refer to the current class itself within the scope of that class
only whereas, $this is used to refer to the member variables and function for a particular
instance of a class.

PHP self operator: The self operator represents the current class and thus is used to
access class variables or static variables because these members belong to a class
rather than the object of that class.

Syntax:​

self::$static_member

PHP $this operator: The $this, as the ‘$’ sign suggests, is an object. $ This represents
the current object of a class. It is used to access non-static members of a class.

Syntax:​

$this->$non_static_member;

Example:​

<?php​
​ class StudentDetail{​

​ ​ public $name;​
​ ​ public static $age;​

​ ​ public function getName() {​
​ ​ ​ return $this->name;​
​ ​ }​
​ ​
​ ​ public static function getAge() {​
​ ​ ​ return self::$age;​
​ ​ }​
​ ​ ​
​ ​ public function getStudentAge() {​
​ ​ ​ return self::getAge();​
​ ​ }​
​ }​
​ ​
​ $obj = new StudentDetail();​

​ $obj->name = "Python";​

​ StudentDetail::$age = "18";​

​ echo "Name : " .$obj->getName()."\xA";​
​ echo "Age : " .StudentDetail::getStudentAge();​

?>

self $this

this keyword should be


The self keywоrd is nоt рreсeded by antecedent with a $ symbol
аny symbоl, we can use it as it is. whenever referring to the class
members.

In order to access class variables and In order to access class


methods, a scope resolution operator variables and methods, an
is used. arrow operator ( -> ) is used.

The self keyword is used to access $this is used to access the


the static members of the class non-static members of the class
present in the program. present in the program.

Self keyword refers to the class $this could refer to the member
members, but doesn’t point toward variables and function for a
any particular object of the class. selected instance of the class.

Constructor and Destructor:

Constructors are special member functions for initial settings of newly created object
instances from a class, which is the key part of the object-oriented concept in PHP5.

Constructors are the very basic building blocks that define the future object and its
nature. You can say that the Constructors are the blueprints for object creation providing
values for member functions and member variables.

Once the object is initialized, the constructor is automatically called. Destructors are for
destroying objects and automatically called at the end of execution.

In this article, we are going to learn about object-oriented concepts of constructors and
destructors.

Both are special member functions of any class with different concepts but the same
name except destructors are preceded by a ~ Tilda operator.

__construct():
function __construct()
{
// initialize the object and its properties by assigning
//values
}

__destruct():

function __destruct()
{
// destroying the object or clean up resources here
}

Note: The constructor is defined in the public section of the Class. Even the values to
properties of the class are set by Constructors.

Constructor types:
●​ Default Constructor:It has no parameters, but the values to the default
constructor can be passed dynamically.
●​ Parameterized Constructor: It takes the parameters, and also you can pass
different values to the data members.
●​ Copy Constructor: It accepts the address of the other objects as a parameter.

Inheritance: As Inheritance is an object-oriented concept, the Constructors are


inherited from parent class to child class derived from it. Whenever the child class has
constructor and destructor of their own, these are called in order of priority or
preference.

Pre-defined Default Constructor: By using function __construct(), you can define a


constructor.

Note: In the case of Pre-defined Constructor(__construct) and user-defined constructor


in the same class, the Pre-defined Constructor becomes Constructor while user-defined
constructor becomes the normal method.

Example:​

<?PHP​
class Tree​
{​
​ function Tree()​
​ {​
​ ​ echo "Its a User-defined Constructor of the class Tree";​
​ }​

​ function __construct()​
​ {​
​ ​ echo "Its a Pre-defined Constructor of the class Tree";​
​ }​
}​

$obj= new Tree();​
?>

Parameterized Constructor: The constructor of the class accepts arguments or


parameters.
The -> operator is used to set value for the variables. In the constructor method, you
can assign values to the variables during object creation.

Example:​
<?php​

class Employee​
{ ​
​ ​
​ Public $name;​

​ Public $position;​

​ function __construct($name,$position)​

​ {​
​ ​ // This is initializing the class properties​
​ ​ $this->name=$name;​
​ ​ $this->position=$position;​


​ }​ ​
​ function show_details()​
​ {​
​ ​ echo $this->name." : ";​
​ ​ echo "Your position is ".$this->position."\n";​
​ }​
}​
​ ​
$employee_obj= new Employee("Rakesh","developer");​
$employee_obj->show_details();​
​ ​
$employee2= new Employee("Vikas","Manager");​
$employee2->show_details();​

?>

Constructors start with two underscores and generally look like normal PHP functions.
Sometimes these constructors are called as magic functions starting with two
underscores and with some extra functionality than normal methods. After creating an
object of some class that includes constructor, the content of constructor will be
automatically executed.

Note: If the PHP Class has a constructor, then at the time of object creation, the
constructor of the class is called. The constructors have no Return Type, so they do not
return anything not even void.

Copy Constructor in php

A Copy Constructor in PHP is a special constructor method that creates a new object by
copying an existing object. Since PHP does not have a built-in copy constructor like
C++, you need to define one manually.

PHP provides the __clone magic method, which can also be used to create a deep copy
of an object.

<?php​

class Product {​
public string $name;​
public float $price;​

public function __construct(string $name, float $price) {​
$this->name = $name;​
$this->price = $price;​
}​

// Clone method​
public function __clone() {​

}​
}​

$product1 = new Product("Laptop", 1200.50);​

// Cloning the object​
$product2 = clone $product1;​

// Modifying the cloned object​
$product2->price = 1500.00;​

echo "Product 1 Price: " . $product1->price . PHP_EOL; // 1200.50​
echo "Product 2 Price: " . $product2->price . PHP_EOL; // 1500.00​

?>

Advantages of using Constructors:

●​ Constructors provides the ability to pass parameters which are helpful in


automatic initialization of the member variables during creation time .
●​ The Constructors can have as many parameters as required and they can be
defined with the default arguments.
●​ They encourage re-usability avoiding re-initializing whenever instance of the
class is created .
●​ You can start session in constructor method so that you don’t have to start in all
the functions everytime.
●​ They can call class member methods and functions.
●​ They can call other Constructors even from Parent class.

Note : The __construct() method always have the public visibility factor.

Destructor

Destructor is also a special member function which is exactly the reverse of constructor
method and is called when an instance of the class is deleted from the memory.
Destructors (__destruct ( void): void) are methods which are called when there is no
reference to any object of the class or goes out of scope or about to release explicitly.
They don’t have any types or return value. It is just called before de-allocating memory
for an object or during the finish of execution of PHP scripts or as soon as the execution
control leaves the block.
Global objects are destroyed when the full script or code terminates. Cleaning up of
resources before memory release or closing of files takes place in the destructor
method, whenever they are no longer needed in the code. The automatic destruction of
class objects is handled by PHP Garbage Collector.

Note: The destructor method is called when the PHP code is executed completely by its
last line by using PHP exit() or die() functions.

<?php​
class SomeClass​
​ {​

​ ​ function __construct()​
​ ​ {​
​ ​ ​ echo "In constructor, ";​
​ ​ ​ $this->name = "Class object! ";​
​ ​ }​

​ ​ function __destruct()​
​ ​ {​
​ ​ ​ echo "destroying " . $this->name . "\n";​
​ ​ }​
​ }​
$obj = new Someclass(); ​

?>

Note: In the case of inheritance, and if both the child and parent Class have destructors
then, the destructor of the derived class is called first, and then the destructor of the
parent class.

Advantages of destructors:

●​ Destructors give chance to objects to free up memory allocation , so that enough


space is available for new objects or free up resources for other tasks.
●​ It effectively makes programs run more efficiently and are very useful as they
carry out clean up tasks.

Comparison between __constructors and __destructors:

Constructors Destructors

Accepts one or more arguments. No arguments are passed. Its void.

function name is _construct(). function name is _destruct()


It has same name as the class with
It has same name as the class.
prefix ~tilda.

Constructor is involved Destructor is involved


automatically when the object is automatically when the object is
created. destroyed.

Used to de-initialize objects


Used to initialize the instance of a
already existing to free up memory
class.
for new accommodation.

Used to initialize data members of Used to make the object perform


class. some task before it is destroyed.

Constructors can be overloaded. Destructors cannot be overloaded.

It is called each time a class is It is called automatically at the time


instantiated or object is created. of object deletion .
Allocates memory. It deallocates memory.

Multiple constructors can exist in Only one Destructor can exist in a


a class. class.

If there is a derived class


inheriting from base class and the
The destructor of the derived class
object of the derived class is
is called and then the destructor of
created,
base class just the reverse order of

the constructor of base class is


constructor.
created and then the constructor
of the derived class.

The concept of copy constructor is


allowed where an object is
initialized from the address of
No such concept is allowed.
another object .

What is Inheritance in PHP?


Inheritance is a fundamental object-oriented programming concept in PHP where a
class (subclass or child class) can inherit properties and methods from another class
(superclass or parent class). It enables code reusability and promotes hierarchical
relationships between classes.
Syntax:​
// Parent class​
class Animal {​
public $species;​

public function sound() {​
return "Animal makes a sound.";​
}​
}​

// Child class inheriting from Animal​
class Dog extends Animal {​
public function sound() {​
return "Dog barks.";​
}​
}

Explanation: To implement inheritance in PHP, use the extends keyword followed by the
name of the parent class. The child class inherits all public and protected properties and
methods from the parent class.

Accessing Parent Class Members:


Child classes can access parent class properties and methods using the parent::
keyword.

Constructor in Inheritance:
Child classes can have their own constructors, which can optionally call the parent class
constructor using parent::__construct( ).

Types of inheritance:
In PHP, inheritance is a fundamental concept of object-oriented programming (OOP)
that allows a class to inherit properties and methods from another class. There are
several types of inheritance in PHP:
1. Single Inheritance
A child class inherits from a single parent class.

class ParentClass {​
public function showMessage() {​
echo "This is the parent class.";​
}​
}​

class ChildClass extends ParentClass {​
}​

$obj = new ChildClass();​
$obj->showMessage(); // Output: This is the parent class.

2. Multilevel Inheritance
A class is derived from another derived class.
class Grandparent {​
public function grandMessage() {​
echo "This is the grandparent class.";​
}​
}​

class ParentClass extends Grandparent {​
public function parentMessage() {​
echo "This is the parent class.";​
}​
}​

class ChildClass extends ParentClass {​
}​

$obj = new ChildClass();​
$obj->grandMessage(); // Output: This is the grandparent class.

3. Hierarchical Inheritance
Multiple child classes inherit from the same parent class.
class ParentClass {​
public function parentMessage() {​
echo "This is the parent class.";​
}​
}​

class ChildClass1 extends ParentClass {​
}​

class ChildClass2 extends ParentClass {​
}​

$obj1 = new ChildClass1();​
$obj1->parentMessage(); // Output: This is the parent class.​

$obj2 = new ChildClass2();​
$obj2->parentMessage(); // Output: This is the parent class.

4. Multiple Inheritance (Using Traits)


PHP does not support multiple inheritance directly, but traits can be used to achieve
similar functionality.

trait TraitOne {​
public function methodOne() {​
echo "This is method from TraitOne.";​
}​
}​

trait TraitTwo {​
public function methodTwo() {​
echo "This is method from TraitTwo.";​
}​
}​

class ChildClass {​
use TraitOne, TraitTwo;​
}​

$obj = new ChildClass();​
$obj->methodOne(); // Output: This is method from TraitOne.​
$obj->methodTwo(); // Output: This is method from TraitTwo.

Abstract Classes and Interfaces in PHP

Abstract classes in php and interface in php are important concepts in object-oriented
programming (OOP) in PHP. An abstract class serves as a blueprint for other classes
and cannot be instantiated on its own. It can contain both concrete and abstract
methods. Abstract methods define the method signatures without providing any
implementation. Interfaces, on the other hand, define a contract that classes must
adhere to. They consist only of method signatures and constants, without any
implementation. Classes can implement multiple interfaces but can inherit from only one
abstract class. Both abstract classes and interfaces provide a way to enforce structure,
standardize behavior, and promote code reusability in PHP applications.

What are Abstract Classes in PHP?

Abstract class in php is a class that cannot be instantiated directly but serves as a
blueprint for other classes. It provides a way to define common properties and methods
that can be inherited by its subclasses, which are regular classes that extend the
abstract class.

An abstract class is declared using the abstract keyword before the class keyword. It
can have both regular methods with implementations and abstract methods without any
implementation. Abstract methods are declared without a body and are meant to be
implemented by the subclasses. 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,
allowing you to define common functionality and enforce certain method
implementations in the subclasses. This promotes code reusability and helps in
organizing and structuring your codebase.

It's important to note that abstract class in php cannot be instantiated directly, meaning
you cannot create objects of the abstract class itself. However, you can create objects
of its subclasses, which inherit the properties and methods defined in the abstract class.
Example:​

abstract class AbstractClass


{
public function showNormalFunction(){
echo "this is normal function";
}

public abstract function showAbstractFunction();


}

class ChildClass extends AbstractClass


{
public function showAbstractFunction()
{
echo "This is abstract method";
}
}

$obj = new ChildClass();


$obj->showNormalFunction();
$obj->showAbstractFunction();


// Abstract Class​
abstract class Animal {​
protected $name;​

public function __construct($name) {​
$this->name = $name;​
}​

abstract public function makeSound();​
}​

// Concrete Class​
class Dog extends Animal {​
public function makeSound() {​
return "Woof!";​
}​
}​

// Concrete Class​
class Cat extends Animal {​
public function makeSound() {​
return "Meow!";​
}​
}​

// Interface​
interface Jumpable {​
public function jump();​
}​

// Concrete Class implementing Interface​
class Kangaroo extends Animal implements Jumpable {​
public function makeSound() {​
return "Boing!";​
}​

public function jump() {​
return "Kangaroo is jumping!";​
}​
}​

// Usage​
$dog = new Dog("Buddy");​
echo $dog->makeSound(); // Output: Woof!​

$cat = new Cat("Whiskers");​
echo $cat->makeSound(); // Output: Meow!​

$kangaroo = new Kangaroo("Joey");​
echo $kangaroo->makeSound(); // Output: Boing!​
echo $kangaroo->jump(); // Output: Kangaroo is jumping!
In this example, we have an abstract class Animal that defines a property $name and
an abstract method makeSound(). The Dog and Cat classes extend the Animal class
and provide their own implementation of the makeSound() method. Run the above code
in your editor for a better and clear explanation.

Some Important Facts About Abstract Classes in PHP


●​ Abstract classes cannot be instantiated directly: You cannot create objects of an
abstract class using the new keyword. They are meant to be extended by
subclasses.
●​ Abstract classes can have both regular and abstract methods: Abstract methods
are declared without a body and are meant to be implemented by the
subclasses. Regular methods in an abstract class can have an implementation
and can be inherited by subclasses.
●​ Subclasses must implement all abstract methods: Any class that extends an
abstract class must provide implementations for all the abstract methods defined
in the abstract class. Failure to do so will result in a fatal error.
●​ Abstract classes can have properties: Abstract classes can define properties,
which can be inherited by subclasses. These properties can have default values
or be overridden in the subclasses.
●​ Abstract classes can be used as type hints: Abstract classes can be used as type
hints in method parameters and return types. This allows you to enforce that a
passed object or returned value is an instance of a specific abstract class or one
of its subclasses.
●​ A class can only extend one abstract class: In PHP, a class can only inherit from
a single abstract class. Multiple inheritance is not supported. However, a class
can implement multiple interfaces while extending an abstract class.

What are Interface in PHP?


Interface in php is a programming construct that defines a contract of methods that a
class must implement. It serves as a blueprint for implementing classes, specifying
which methods must be present and what parameters they should accept and return.
An interface declares the method signatures but does not provide any implementation
details.

To declare an interface in PHP, you use the interface keyword. Inside the interface, you
define the method signatures without any implementation code. These methods are
implicitly assumed to be public and must be implemented with the same visibility in the
classes that implement the interface.
A class can implement multiple interfaces by using the implements keyword followed by
a comma-separated list of interface names. When a class implements an interface, it
must provide implementations for all the methods declared in that interface. Failure to
do so will result in a fatal error.

Example:​
// Interface​
interface Vehicle {​
public function start();​
public function stop();​
}​

// Class implementing the interface​
class Car implements Vehicle {​
public function start() {​
echo "Car started." . PHP_EOL;​
}​

public function stop() {​
echo "Car stopped." . PHP_EOL;​
}​
}​

// Class implementing the interface​
class Motorcycle implements Vehicle {​
public function start() {​
echo "Motorcycle started." . PHP_EOL;​
}​

public function stop() {​
echo "Motorcycle stopped." . PHP_EOL;​
}​
}​

// Usage​
$car = new Car();​
$car->start(); // Output: Car started.​
$car->stop(); // Output: Car stopped.​

$motorcycle = new Motorcycle();​
$motorcycle->start(); ​
$motorcycle->stop();

In this example, we have an interface called Vehicle that defines two methods: start()
and stop(). The Car class and Motorcycle class both implement the Vehicle interface,
meaning they provide an implementation for both methods defined in the interface. Run
the above code in your editor for a better and clear explanation.

By implementing the interface, the Car and Motorcycle classes guarantee that they will
have the start() and stop() methods available. This allows us to create objects of these
classes and call these methods, providing a consistent interface for interacting with
different types of vehicles.

Interface Class Abstract Class

Interface class supports multiple Abstract class does not support


inheritance feature multiple inheritances.

This does not contain a data member. Abstract class does contain a data
member.

The interface does not allow containers. The abstract class supports
containers.

An interface class only contains Abstract class contains both


incomplete members which refer to the incomplete(i.e. abstract) and complete
signature of the member. members.

Since everything is assumed to be public, An abstract class can contain access


an interface class does not have access modifiers within subs, functions, and
modifiers by default. properties.

Any member of an interface cannot be Only a complete member of the


static. abstract class can be static.
Concrete Classes
A concrete class is a class that can be instantiated, which means you can create
objects of that class. It provides the actual implementation of the methods defined in the
interface or abstract class that it implements or extends.

For example, let’s say you have an abstract class named “Animal” that defines the basic
properties and methods of an animal. You also have two concrete classes named “Dog”
and “Cat” that extend the “Animal” abstract class.

abstract class Animal {​


protected $name;​
protected $age;​

public function __construct($name, $age) {​
$this->name = $name;​
$this->age = $age;​
}​

abstract public function makeSound();​
}​

class Dog extends Animal {​
public function makeSound() {​
return "Woof!";​
}​
}​

class Cat extends Animal {​
public function makeSound() {​
return "Meow!";​
}​
}

In the above example, the “Animal” class is an abstract class that defines the basic
properties and methods of an animal. The “Dog” and “Cat” classes are concrete classes
that implement the “makeSound” method defined in the “Animal” class. They provide
their own implementation of the “makeSound” method, which makes them different from
each other.

Now, you can create objects of the “Dog” and “Cat” classes and call their respective
methods:

$dog = new Dog("Rufus", 2);​


echo $dog->makeSound(); // Output: Woof!​

$cat = new Cat("Fluffy", 1);​
echo $cat->makeSound(); // Output: Meow!

In the above example, you can create objects of the “Dog” and “Cat” classes and call
their “makeSound” method. Since the “Dog” and “Cat” classes implement the
“makeSound” method defined in the “Animal” abstract class, you can use the
“makeSound” method of the “Dog” and “Cat” objects without any issues.
Web Based Application Development with
PHP
Day 3.3:

Chapter 3: Apply Object Oriented Concepts in PHP

●​ Overloading and overriding


●​ Types of overloading
●​ Final keyword
●​ Cloning object
●​ Deep copy and shallow copy
●​ Introspection and serialization

Overloading and overriding

Function overloading and overriding is the OOPs feature in PHP. In function


overloading, more than one function can have same method signature but different
number of arguments. But in case of function overriding, more than one functions will
have same method signature and number of arguments.

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.

<?php​
// PHP program to explain function ​
// overloading in PHP​

// Creating a class of type shape​
class shape {​
​ ​
​ // __call is magic function which accepts ​
​ // function name and arguments​
​ function __call($name_of_function, $arguments) {​
​ ​ ​ ​
​ ​ // It will match the function name​
​ ​ if($name_of_function == 'area') {​
​ ​ ​ ​
​ ​ ​ switch (count($arguments)) {​
​ ​ ​ ​ ​ ​
​ ​ ​ ​ // If there is only one argument​
​ ​ ​ ​ // area of circle​
​ ​ ​ ​ case 1:​
​ ​ ​ ​ ​ return 3.14 * $arguments[0];​
​ ​ ​ ​ ​ ​ ​
​ ​ ​ ​ // IF two arguments then area is rectangle;​
​ ​ ​ ​ case 2:​
​ ​ ​ ​ ​ return $arguments[0]*$arguments[1];​
​ ​ ​ }​
​ ​ }​
​ }​
}​
​ ​
// Declaring a shape type object​
$s = new Shape;​
​ ​
// Function call ​
echo($s->area(2));​
echo "\n";​
​ ​
// calling area method for rectangle​
echo ($s->area(4, 2));​
?>

Function Overriding:
Function overriding is same as other OOPs programming languages. In function
overriding, both parent and child classes should have same function name with and
number of arguments. It is used to replace parent method in child class. The purpose of
overriding is to change the behavior of parent class method. The two methods with the
same name and same parameter is called overriding.

<?php​
// PHP program to implement ​
// function overriding​

// This is parent class​
class P {​
​ ​
​ // Function show of parent class​
​ function show() {​
​ ​ echo "Parent";​
​ }​
}​

// This is child class​
class C extends P {​
​ ​
​ // Overriding show method​
​ function show() {​
​ ​ echo "\nChild";​
​ }​
}​

// Reference type of parent​
$p = new P;​

// Reference type of child​
$c= new C;​

// print Parent​
$p->show();​

// Print child​
$c->show();​
?>
Property and Rules of overloading in PHP:

●​ All overloading methods must be defined as Public.


●​ After creating the object for a class, we can access a set of entities that are
properties or methods not defined within the scope of the class.
●​ Such entities are said to be overloaded properties or methods, and the process is
called as overloading.
●​ For working with these overloaded properties or functions, PHP magic methods
are used.
●​ Most of the magic methods will be triggered in object context except
__callStatic() method which is used in a static context.

Types of Overloading in PHP

●​ Property Overloading
●​ Method Overloading

Property Overloading:
PHP property overloading is used to create dynamic properties in the object context.
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. Following operations are performed with overloaded
properties in PHP.
●​ Setting and getting overloaded properties.
●​ Evaluating overloaded properties setting.
●​ Undo such properties setting.

Before performing the operations, we should define appropriate magic methods. which
are,

●​ __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.

<?php​

// ​
class ABC {​
​ ​
​ // Location of overloading data​
​ private $data = array();​

​ // Overloading not used here​
​ public $declared = 1;​

​ // Overloading used when accessed​
​ // outside the class​
​ private $hidden = 2;​
​ ​
​ // Function definition​
​ public function __set($name, $value) {​
​ ​ echo "Setting '$name' to '$value'\n";​
​ ​ $this->data[$name] = $value;​
​ }​
​ ​
​ // Function definition​
​ public function __get($name) {​
​ ​ echo "Getting '$name: ";​
​ ​ if (array_key_exists($name, $this->data)) {​
​ ​ ​ return $this->data[$name];​
​ ​ }​

​ ​ $trace = debug_backtrace();​
​ ​ ​
​ ​ return null;​
​ }​

​ // Function definition​
​ public function __isset($name) {​
​ ​ echo "Is '$name' set?\n";​
​ ​ return isset($this->data[$name]);​
​ }​

​ // Definition of __unset function​
​ public function __unset($name) {​
​ ​ echo "Unsetting '$name'\n";​
​ ​ unset($this->data[$name]);​
​ }​

​ // getHidden function definition​
​ public function getHidden() {​
​ ​ return $this->hidden;​
​ }​
}​

// Create an object​
$obj = new ABC;​

// Set value 1 to the object variable​
$obj->a = 1;​
echo $obj->a . "\n";​

// Use isset function to check​
// 'a' is set or not​
var_dump(isset($obj->a));​

// Unset 'a'​
unset($obj->a);​

var_dump(isset($obj->a));​

echo $obj->declared . "\n\n";​

echo "Private property are visible inside the class ";​
echo $obj->getHidden() . "\n\n";​

echo "Private property are not visible outside of class\n";​
echo $obj->hidden . "\n";​

?>

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.

<?php​
class ABC{​
​ ​
​ 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​
$obj = new ABC;​

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

ABC::runTest('in static context'); ​

?>

Final keyword

Final keyword in PHP is used in different context. The final keyword is used only for
methods and classes.
Final methods:
When a method is declared as final then overriding on that method can not be
performed. Methods are declared as final due to some design reasons. Method should
not be overridden due to security or any other reasons.

<?php ​

// Program to understand use of ​
// final keyword for methods ​
class Base { ​
​ ​
​ // Final method ​
​ final function printdata() { ​
​ ​ echo " Base class final printdata function"; ​
​ } ​
​ ​
​ // Non final method ​
​ function nonfinal() { ​
​ ​ echo "\n This is nonfinal function of base class"; ​
​ } ​
} ​

// Class that extend base class ​
class Derived extends Base { ​
​ ​
​ // Inheriting method nonfinal ​
​ function nonfinal() { ​
​ ​ echo "\n Derived class non final function"; ​
​ } ​
​ ​
​ // Here printdata function can ​
​ // not be overridden ​
} ​

$obj = new Derived; ​
$obj->printdata(); ​
$obj->nonfinal(); ​
?>

Final Classes:
A class declared as final can not be extended in future. Classes are declared as final
due to some design level issue. Creator of class declare that class as final if he want
that class should not be inherited due to some security or other reasons. A final class
can contain final as well as non final methods. But there is no use of final methods in
class when class is itself declared as final because inheritance is not possible.

<?php ​

// Program to understand final classes ​
// in php ​
final class Base { ​
​ ​
​ // Final method ​
​ final function printdata() { ​
​ ​ echo "final base class final method"; ​
​ } ​
​ ​ ​
​ // Non final method ​
​ function nonfinal() { ​
​ ​ echo "\nnon final method of final base class"; ​
​ } ​
} ​

$obj = new Base; ​
$obj->printdata(); ​
$obj->nonfinal(); ​

/* If we uncomment these lines then it will ​
show Class Derived may not inherit from final ​
class (Base) ​
class Derived extends Base { ​
​ ​
} */​
?>

Cloning Objects

A PHP statement such as "$obj1 = $obj2" merely creates another reference to the same
object in memory. Hence, changes in attribute reflect both in original and duplicate
object. The clone keyword in PHP creates a shallow copy of an object.
<?php​
class foo {​
var $var1 = 'Hello';​
}​
$x = new foo();​
$y = $x;​ ​ # reference copy​
echo $x->var1 . " " . $y->var1 . PHP_EOL;​

$x->var1 = "Hello World";​
echo $x->var1 . " " . $y->var1 . PHP_EOL;​
?>

Using the "clone" Keyword

In a shallow copy, any properties of the original object that are references to other
variables will remain references. The clone keyword does not copy the contained
objects of the copied objects.

We now create a clone of myclass object, so that $obj2 is the clone of $obj1. We
change the name property of $obj1 from Raja to Ravi, and also modify the embedded
address object. The property change will not reflect in its clone, but the referred address
object will be changed.
<?php​
class address {​
var $city="Nanded";​
var $pin="431601";​
function setaddr($arg1, $arg2) {​
$this->city=$arg1;​
$this->pin=$arg2;​
}​
}​
class myclass {​
var $name="Raja";​
var $obj;​
function setname($arg) {​
$this->name=$arg;​
}​
}​
$obj1=new myclass();​
$obj1->obj=new address();​
echo "original object\n";​
print_r($obj1);​
echo "\n";​

$obj2=clone $obj1;​ ​ # clone copy​
$obj1->setname("Ravi");​
$obj1->obj->setaddr("Mumbai", "400001");​
echo "after change: Original object\n";​
print_r($obj1);​
echo "\nCopied object\n";​
print_r($obj2);​
?>

Using __clone() Method


The clone keyword creates a shallow copy of the object. When an object is cloned, PHP
will perform a shallow copy of all of the object's properties. Any properties that are
references to other variables will remain references. Hence, any changes done to the
original object will also appear in the cloned object.

If you wish to prevent the copied object to update automatically, we need to create a
deep copy of the object with the __clone() method. It is one of the magic methods in
PHP.
Once the cloning is complete, if a __clone() method is defined, then the newly created
object's __clone() method will be called, to allow any necessary properties that need to
be changed.

<?php​
class address {​
var $city="Nanded";​
var $pin="431601";​
function setaddr($arg1, $arg2) {​
$this->city=$arg1;​
$this->pin=$arg2;​
}​
}​
class myclass {​
var $name="Raja";​
var $obj;​
function setname($arg) {​
$this->name=$arg;​
}​
public function __clone() {​
$this->obj = clone $this->obj ;​
}​
}​
$obj1=new myclass();​
$obj1->obj=new address();​
echo "original object\n";​
print_r($obj1);​
echo "\n";​

$obj2=clone $obj1;​ ​ # cloned deep copy​
$obj1->setname("Ravi");​
$obj1->obj->setaddr("Mumbai", "400001");​
echo "after change: Original object\n";​
print_r($obj1);​
echo "\nCloned object\n";​
print_r($obj2);​
?>
Deep copy and shallow copy

Shallow Copy: Shallow repetition is quicker. However, it’s “lazy” it handles pointers and
references. Rather than creating a contemporary copy of the particular knowledge the
pointer points to, it simply copies over the pointer price. So, each of the first and
therefore the copy can have pointers that reference constant underlying knowledge.

Deep Copy: Deep repetition truly clones the underlying data. It is not shared between
the first and therefore the copy.

Shallow Copy Deep Copy

Shallow Copy stores the


Deep copy stores copies of the
references of objects to the
object’s value.
original memory address.

Shallow Copy reflects changes Deep copy doesn’t reflect changes


made to the new/copied object in made to the new/copied object in
the original object. the original object.

Shallow Copy stores the copy of Deep copy stores the copy of the
the original object and points the original object and recursively
references to the objects. copies the objects as well.
A shallow copy is faster. Deep copy is comparatively slower.

Introspection and serialization

Most often we need to store a complex array in the database or in a file from PHP.
Some of us might have surely searched for some built-in function to accomplish this
task. Complex arrays are arrays with elements of more than one data-types or array.

But, we already have a handy solution to handle this situation. We don’t have to write
our own function to convert the complex array to a formatted string. There are two
popular methods of serializing variables.

●​ serialize()
●​ unserialize()

We can serialize any data in PHP using the serialize() function. The serialize() function
accepts a single parameter which is the data we want to serialize and returns a
serialized string. Below program illustrate this:

<?php ​

// a complex array ​
$myvar = array( ​
​ 'hello', ​
​ 42, ​
​ array(1, 'two'), ​
​ 'apple'​
); ​

// convert to a string ​
$string = serialize($myvar); ​

// printing the serialized data ​
echo $string; ​

?>

From the above code, we have a variable with serialized data, $string . We can
unserialize the value of the variable using unserialize() function to get back to the
original value of the complex array, $myvar.

Below program illustrate both serialize() and unserialize() functions:

<?php ​

// a complex array ​
$myvar = array( ​
​ 'hello', ​
​ 42, ​
​ array(1, 'two'), ​
​ 'apple'​
); ​

// serialize the above data ​
$string = serialize($myvar); ​

// unserializing the data in $string ​
$newvar = unserialize($string); ​

// printing the unserialized data ​
print_r($newvar); ​

?>

You might also like