Chapter - 3 Apply Object Oriented Concepts in PHP Marks-16: Notes by - G. R. Jagtap 1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Chapter – 3

Apply Object Oriented Concepts in PHP


Marks- 16

Content outline:
3.1 Creating Classes and Objects
3.2 Constructor and Destructor
3.3 Inheritance, Overloading and Overriding, Cloning Object
3.4 Introspection, Serialization

3.1 Creating Classes and Objects


Q. What is the use of OOP?
Ans:
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:
• OOP is faster and easier to execute
• OOP provides a clear structure for the programs
• OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code easier to
maintain, modify and debug
• OOP makes it possible to create full reusable applications with less code and shorter
development time

Q. List out Object Oriented Concepts.


Ans:
Important terms related to Object Oriented Programming are-
• Class − This is a programmer-defined data type, which includes local functions as well as
local data. You can think of a class as a template for making many instances of the same kind
(or class) of object.
• Object − An individual instance of the data structure defined by a class. You define a class
once and then make many objects that belong to it. Objects are also known as instance.

Notes By- G. R. Jagtap


1
• Member Variable − These are the variables defined inside a class. This data will be invisible
to the outside of the class and can be accessed via member functions. These variables are
called attribute of the object once an object is created.
• Member function − These are the function defined inside a class and are used to access object
data.
• Inheritance − When a class is defined by inheriting existing function of a parent class then it
is called inheritance. Here child class will inherit all or few member functions and variables
of a parent class.
• Parent class − A class that is inherited from by another class. This is also called a base class
or super class.
• Child Class − A class that inherits from another class. This is also called a subclass or derived
class.
• Polymorphism − This is an object oriented concept where same function can be used for
different purposes. For example function name will remain same but it take different number
of arguments and can do different task.
• Overloading − a type of polymorphism in which some or all of operators have different
implementations depending on the types of their arguments. Similarly functions can also be
overloaded with different implementation.
• Data Abstraction − Any representation of data in which the implementation details are
hidden (abstracted).
• Encapsulation − refers to a concept where we encapsulate all the data and member functions
together to form an object.
• Constructor − refers to a special type of function which will be called automatically whenever
there is an object formation from a class.
• Destructor − refers to a special type of function which will be called automatically whenever
an object is deleted or goes out of scope.

Q. How classes are defined in PHP? Explain with example.


Ans:
The general form for defining a new class in PHP is as follows –
<?php
class phpClass {
var $var1;
var $var2 = "constant string";

Notes By- G. R. Jagtap


2
function myfunc ($arg1, $arg2) {
[..]
}
[..]
}
?>
Here is the description of each line −
• The special form class, followed by the name of the class that you want to define.
• A set of braces enclosing any number of variable declarations and function definitions.
• Variable declarations start with the special form var, which is followed by a conventional $
variable name; they may also have an initial assignment to a constant value.
• Function definitions look much like standalone PHP functions but are local to the class and
will be used to set and access object data.
<?php
class Books {
/* Member variables */
var $price;
var $title;

/* Member functions */
function setPrice($par){
$this->price = $par;
}

function getPrice(){
echo $this->price ."<br/>";
}

function setTitle($par){
$this->title = $par;
}

function getTitle(){

Notes By- G. R. Jagtap


3
echo $this->title ." <br/>";
}
}
$physics = new Books();
$maths = new Books();
$chemistry = new Books();
$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );

$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();

?>
The variable $this is a special variable and it refers to the same object ie. itself.
Creating Objects in PHP
Once class is defined, then create as many objects as required of that class type. Following is an
example of how to create object using new operator.
$physics = new Books();
Calling Member Functions
After creating your objects, you will be able to call member functions related to that object. One
member function will be able to process member variable of related object only.
Following example shows how to set title and prices for the three books by calling member functions.
$physics->setTitle( "Physics for High School" );
$physics->setPrice( 10 );
$physics->getTitle();
$physics->getPrice();

Notes By- G. R. Jagtap


4
Q. Write a PHP script to define a class Fruit with data members name and color. Accept and
display data for one object.
Ans:
<?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();
?>
Q. Explain Access specifiers.
Ans:
Access specifiers are –

Notes By- G. R. Jagtap


5
i. Public – the property ie. Data member and functions which are defined using public access
specifier can be accessed from outside of class.
ii. Private - the property ie. Data member and functions which are defined using private access
specifier can be accessed by the members of class only. No access is granted to outside of the
class.
iii. Protected - the property ie. Data member and functions which are defined using public access
specifier can be accessed from the class and its inherited i.e child class.
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
?>
Example of private
class MyClass
{
private $car = "skoda";
$driver = "SRK";

function myPublicFunction() {
return("I'm visible!");
}

private function myPrivateFunction() {


return("I'm not visible outside!");
}
}

Notes By- G. R. Jagtap


6
Example of protected
class MyClass
{
protected $car = "skoda";
$driver = "SRK";

function myPublicFunction() {
return("I'm visible!");
}

protected function myPrivateFunction() {


return("I'm visible in child class!");
}
}

Q. What is the use of $this?


Ans:
• $this is a special variable which is used to access properties and methods of a class within
same class.
• The $this keyword refers to the current object, and is only available inside methods.
<?php
class Fruit
{
public $name;
function set_name($name) {
$this->name = $name;
}
}
$apple = new Fruit();
$apple->set_name("Apple");
?>

Notes By- G. R. Jagtap


7
3.2 Constructor and Destructor

Q. Explain use of constructor and destructor with suitable example.


Ans:
• Constructor Functions are special type of functions which are called automatically whenever
an object is created.
• Constructors are used for initializing objects.
• PHP provides a special function called __construct() to define a constructor.
• Parameters can be passed into the constructor function.
• Example
<?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit("Apple");


echo $apple->get_name();
?>
• Like a constructor function you can define a destructor function using function __destruct().
All the resources can be released with-in a destructor.
• A destructor is called when the object is destructed or the script is stopped or exited.
• A __destruct() function, PHP will automatically call this function at the end of the script.
• Example
<?php
class Fruit {

Notes By- G. R. Jagtap


8
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}

$apple = new Fruit("Apple");


?>

3.3 Inheritance, Overloading and Overriding, Cloning Object

Q. Define Inheritance. List types of Inheritance.


Ans:
• Inheritance in OOP = When a class derives from another class.
• 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.
• Example
<?php
class Fruit
{
public $name;
public $color;
public function __construct($name, $color)
{
$this->name = $name;
$this->color = $color;
}

Notes By- G. R. Jagtap


9
protected function intro()
{
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}

class Strawberry extends Fruit


{
public function message()
{
echo "Am I a fruit or a berry? ";
}
}

// Try to call all three methods from outside class


$strawberry = new Strawberry("Strawberry", "red"); // OK. __construct() is public
$strawberry->message(); // OK. message() is public
$strawberry->intro(); // ERROR. intro() is protected
?>
Types of Inheritance
1)Single Inheritance
2)Hierarchical Inheritance
3)Multilevel Inheritance
4)Multiple Inheritance
5)Hybrid Inheritance

Q. Explain single inheritance with suitable example.


Ans:
In single inheritance, there is one base class and one derived class.
<?php
class A
{
function showA()
{

Notes By- G. R. Jagtap


10
echo “Inside class A”;
}
}
class B extends A
{
function showB()
{
echo “Inside class B”;
}
}
$obj=new B();
$obj->showA();
$obj->showB();
?>

Q. Explain multilevel inheritance with suitable example.


Ans:
<?php
class A
{
function showA()
{
echo “Inside class A”;
}
}
class B extends A
{
function showB()
{
echo “Inside class B”;
}
}
class C extends B
{

Notes By- G. R. Jagtap


11
function showC()
{
echo “Inside class C”;
}
}

$obj=new C();
$obj->showA();
$obj->showB();
$obj->showC();
?>

Q. Explain hierarchical inheritance with suitable example.


Ans:
<?php
class A
{
function showA()
{
echo “Inside class A”;
}
}
class B extends A
{
function showB()
{
echo “Inside class B”;
}
}
class C extends A
{
function showC()
{
echo “Inside class C”;

Notes By- G. R. Jagtap


12
}
}
$obj1=new B();
$obj1->showA();
$obj1->showB();
$obj2=new C();
$obj2->showA();
$obj2->showC();
?>

Q. Explain – Overloading and Overriding


Ans:
Overloading
- When multiple methods defined with same name and different prototype in class, it is called
overloading
- Example
<?php
class ArithOp
{
function add() // function-1
{
$a=5;
$b=3;
echo “Addition is –“.($a+$b);
}
function add($x,$y) function-2
{
$a=$x;
$b=$y;
echo “Addition is –“.($a+$b);
}
}
$obj=new ArithOp();
$obj->add(); //it will invoke function-1

Notes By- G. R. Jagtap


13
$obj->add(5,2); //it will invoke function-2
?>
Overriding
- If a subclass contains a method with same name and signature as it is defined in its
superclass, it is called as overriding.
- Example
<?php
class A
{
function show()
{
echo “Inside class A”;
}
}
class B extends A
{
function show()
{
echo “Inside class B”;
}
}
$obj1=new A();
$obj1->show(); // it will call superclass i.e class A method
$obj2=new B();
$obj2->show(); //it will call subclass i.e class B method
?>

Q. Explain the concept of abstract class with suitable example.


Ans:
- An abstract class is one that cannot be instantiated, only inherited.
- When inheriting from an abstract class, all methods marked abstract in the parent's class
declaration must be defined by the child; additionally, these methods must be defined
with the same visibility.
- An abstract class is a class that contains at least one abstract method.

Notes By- G. R. Jagtap


14
- 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:
- Syntax
abstract class MyAbstractClass {
abstract function myAbstractFunction() {
}
}

- Example
<?php
// Parent class
abstract class Car {
public $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function intro() : string;
}

// Child classes
class Audi extends Car {
public function intro() : string {
return "Choose German quality! I'm an $this->name!";
}
}
class Volvo extends Car {
public function intro() : string {
return "Proud to be Swedish! I'm a $this->name!";
}
}
// Create objects from the child classes
$audi = new audi("Audi");
echo $audi->intro();
echo "<br>";

Notes By- G. R. Jagtap


15
$volvo = new volvo("Volvo");
echo $volvo->intro();
echo "<br>";
?>

Q. Explain use of Interface with suitable example.


Ans:
- Interfaces are defined to provide a common function names to the implementers.
Different implementors can implement those interfaces according to their requirements.
- Syntax:
interface interface_name {
public function method_name();
}

Q. Explain the use of final with suitable example.


Ans:
- “final” keyword, which prevents child classes from overriding a method by prefixing the
definition with final.
- If the class itself is being defined final then it cannot be extended.
- The final keyword can be used to prevent class inheritance or to prevent method
overriding.
- Example
<?php
final class Fruit {
// some code
}

// will result in error


class Strawberry extends Fruit {
// some code
}
?>

The following example shows how to prevent method overriding:

Notes By- G. R. Jagtap


16
<?php
class Fruit {
final public function intro() {
// some code
}
}

class Strawberry extends Fruit {


// will result in error
public function intro() {
// some code
}
}
?>

Q. What is trait? How it is use? Give one example


Ans:
- PHP only supports single inheritance: a child class can inherit only from one single parent.
- So, what if a class needs to inherit multiple behaviors? OOP traits solve this problem.
- 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...
}
?>
- Example
<?php
trait message1
{
public function msg1()

Notes By- G. R. Jagtap


17
{
echo "OOP is fun! ";
}
}
class Welcome
{
use message1;
}
$obj = new Welcome();
$obj->msg1();
?>
example of multiple traits
<?php
trait message1 {
public function msg1() {
echo "OOP is fun! ";
}
}

trait message2 {
public function msg2() {
echo "OOP reduces code duplication!";
}
}

class Welcome {
use message1;
}

class Welcome2 {
use message1, message2;
}

$obj = new Welcome();

Notes By- G. R. Jagtap


18
$obj->msg1();
echo "<br>";

$obj2 = new Welcome2();


$obj2->msg1();
$obj2->msg2();
?>

Q. Explain Concept of Cloning with suitable example.


Ans:
- Object cloning is creating a copy of an object. An object copy is created by using the clone
keyword.
- Example:
<html>
<body>
<?php
class Animals
{
var $name;
var $category;
}
//Creating instance of Animals class
$obj1 = new Animals();
//Assigning values
$obj1->name = "Lion";
$obj1->category = "Wild Animal";
//Cloning the original object
$obj2 = clone $obj1;
$obj2->name = "Elephant";
$obj2->category = "Wild Animal";
print_r($obj1);
echo "<br>";
print_r($obj2);
?>

Notes By- G. R. Jagtap


19
</body>
</html>

3.4 Introspection, Serialization

Q. Explain serialization with suitable example.


Ans:
- 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.
Syntax
serialize(value);
- unserialize() - Convert serialized data back into actual data
Syntax
unserialize(string, options);

<html>
<body>
<?php
$a = array('Manish',42,'Manager',50000);
// Serialize above data.
$ser = serialize($a);
// printing the serialized data
echo "Output of Serialize is - "."<br>".$ser;
echo "<br>";
// unserializing the data in $string
$unser = unserialize($ser);
// printing the unserialized data
echo "Output of Unserialize is - "."<br>";
print_r($unser);
?>
</body>
</html>

Notes By- G. R. Jagtap


20
Q What is introspection? Explain with suitable example.
Ans:
Introspection
- Is the ability of a program to inspect characteristics of object and class, such as name, parent
class, properties and methods.
- With introspection , we can write code which works on any class or object.
- 1) examining classes
$yes_no = class_exists(class_name);
- This method is used to check whether a class exists or not. It returns Boolean value.
$classes = get_declared_classes();
- This method returns an array contacting names of classes which are defined.
$methods = get_class_methods(classname);
- This method returns methods which are present in a class.
$properties = get_class_vars(classname);
- This method returns properties (data members) which are present in a class.
$superclass = get_parent_class(classname)
- This method returns parent class of given classname.

<html>
<body>
<?php
class A
{
public $x;
function initA($a)
{
$this->x = $a;
}
function showA()
{
echo "X:".$this->x;
}
}
class B extends A

Notes By- G. R. Jagtap


21
{
public $y;
function initB($b)
{
$this->y = $b;
}
function showB()
{
echo "Y:".$this->y;
}
}
class C extends B
{
public $z;
function initC($c)
{
$this->z = $c;
}
function showC()
{
echo "Z:".$this->z;
}
}

if(class_exists('B'))
{
$obj1=new B();
echo "Class B exist";
}
else
echo "Class B does not exist";

echo "Parent class is -".get_parent_class($obj1);


echo "<br>";

Notes By- G. R. Jagtap


22
$obj2=new C();
echo " Parent class is -".get_parent_class($obj2);
echo "<br>";
echo "Method of Class B are-";
$m = get_class_methods($obj1);
print_r($m);
echo "<br>";
echo "Properties of Class B are-";
$v = get_class_vars('A');
print_r($v);
echo "<br>";
?>
</body>
</html>

Notes By- G. R. Jagtap


23

You might also like