0% found this document useful (0 votes)
14 views15 pages

TY CO PhP Unit 03

This document provides an overview of Object-Oriented Programming (OOP) concepts in PHP, including classes, objects, constructors, destructors, inheritance, method overriding, and object cloning. It explains how to create classes and objects, the significance of visibility levels, and the use of magic methods for function overloading. Additionally, it covers introspection in PHP, allowing developers to examine class properties and methods dynamically.
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)
14 views15 pages

TY CO PhP Unit 03

This document provides an overview of Object-Oriented Programming (OOP) concepts in PHP, including classes, objects, constructors, destructors, inheritance, method overriding, and object cloning. It explains how to create classes and objects, the significance of visibility levels, and the use of magic methods for function overloading. Additionally, it covers introspection in PHP, allowing developers to examine class properties and methods dynamically.
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/ 15

Unit-III Apply Object Oriented Concepts in PHP

3a Write constructor and destructor functions for the given problem in PHP.
3b Implement inheritance to extend the given base class.
30. Use overloading/overriding to solve the given problem.
3d Clone the given object.
Topics and Sub-topics
3.1 Creating Classes and Objects
3.2 Constructor and Destructor
3.3 Inheritance, Overloading and Overriding, Cloning Object.
3.4 Introspection, Serialization

3.0 INTRODUCTION

Object-Oriented Programming (OOP) is an approach to software development that models


applications around real-world objects such as employees, cars, bank accounts, etc. A class
defines the properties and methods of a real-world object, while an object is an instance of a
class.
PHP is an Object-Oriented Programming Language (OOPL). OOP principles in PHP help in
building complex, reusable web applications. OOP organizes data and structure using classes
and objects, allowing developers to model problems and processes effectively. An object-
oriented application consists of related objects that collaborate to solve a problem. By using
OOP in PHP, we can create modular web applications and perform various activities in an
object model structure.
Different programming languages may use varied terminology for the same concepts. This
chapter focuses on OOP terminology as used in PHP.

Concept of a Class
A class is a blueprint for creating objects. It is a collection of data members (properties) and
functions (methods). The class defines how an object will behave by specifying its properties
and methods.
Components of a Class:
1. Properties – These represent characteristics of an object and can be different types of
data, such as numbers, strings, nulls, and Booleans. Data is stored using variables,
constants, and arrays.
2. Methods – These are functions that define the behavior of an object by operating on its
data.
Example:
Consider a Bike as a class:
 Properties: Color, weight, manufacturer, petrol tank capacity.
 Methods: Accelerate, stop, signal a turn, sound the horn.
These characteristics and behaviors are common to all bikes, and OOP enables us to define
them using a Class construct. In OOP, the characteristics of a class are known as properties,
which have a name and a value.
Concept of an Object
An object is an instance of a class. It represents a real-world entity with specific properties and
behaviors.
Characteristics of an Object:
 Objects have properties (data associated with them).
 Objects have methods (functions that operate on the data).
 Similar objects with the same characteristics and behaviors can be grouped into a single
class.
Example:
A class can be compared to a blueprint for a house:
 The blueprint (Class) defines characteristics such as the number of rooms, windows,
and doors.
 A house (Object) is an instance built from that blueprint. Multiple houses can be
created using the same blueprint.
Thus, a class is like a blueprint, while an object is a tangible realization of that blueprint.

3.1 CREATING CLASSES AND OBJECTS

A class in PHP is a programmer-defined data type that serves as a template for creating multiple
instances of the same kind (or class) of object. A class defines the properties and behaviors
(methods) that an object will have.
3.1.1 Creating Classes
A class is defined using the class keyword, followed by the class name and a pair of curly braces
{}. All properties and methods of the class are declared within these braces.
General Syntax:
class ClassName [extends BaseClass] {
// Properties
var $property_name [= value];

// Methods
function functionName(args) {
// Code...
}
}
Classes are defined with the class keyword, followed by the desired class name. Inside the class,
you can declare variables (properties) and define functions (methods). Both are optional,
meaning you can create an empty class.
 Property declarations start with var, followed by $variable_name.
 Methods (functions) look similar to standalone PHP functions but operate within the
class and can access class properties.
Example: Creating a Class
<?php
class Student {
// Property declaration
var $roll_no = 1; // Default value

// Method definition
function showRollNo() {
echo $this->roll_no;
}
}
?>
3.1.2 Creating an Object
To create an object of a class, use the new keyword.
Syntax:
$object = new ClassName;
Example:
$s1 = new Student;
Here, $s1 is an object of class Student.
Accessing Properties and Methods
Once an object is created, use the -> (object operator) to access its properties and methods.
Syntax:
$object->property_name;
$object->method_name([args]);
Example:
<?php
class Student {
var $roll_no;
var $name;

function display() {
echo "Roll No: " . $this->roll_no . "<br>";
echo "Name: " . $this->name;
}
}

// Creating an object
$s1 = new Student;
$s1->roll_no = 10; // Assigning value to property
$s1->name = "Amar";
$s1->display();
?>
Output:
Roll No: 10
Name: Amar
Understanding $this
 $this is
a reference to the calling object and is available inside any class method.
 Within class methods, non-static properties are accessed using ->.
 Static properties and methods are accessed using the :: (double colon).
Static Methods and Properties
 Static properties and methods can be accessed without creating an object.
 If all methods and properties in a class are static, it is called a static class.
Example of Static Members:
<?php
class Example {
static $staticVar = "Hello";

static function show() {


echo self::$staticVar;
}
}

// Accessing static property and method without object


Example::show();
?>
Concept of Visibility
Visibility determines how class members (properties and methods) can be accessed. PHP
provides three visibility levels:
1. Public Members:
o Default visibility.
o Accessible from anywhere (inside or outside the class).
2. Private Members:
o Only accessible within the class.
o Not accessible from outside the class.
3. Protected Members:
o Accessible within the class and by derived (child) classes.
Example:
<?php
class Example {
public $publicVar = "Public";
private $privateVar = "Private";
protected $protectedVar = "Protected";

function show() {
echo $this->publicVar . "<br>";
echo $this->privateVar . "<br>";
echo $this->protectedVar . "<br>";
}
}

$obj = new Example;


echo $obj->publicVar; // Allowed
$obj->show(); // Allowed
// echo $obj->privateVar; // Error: Cannot access private property
// echo $obj->protectedVar; // Error: Cannot access protected property
?>
Summary
 Classes define a blueprint for objects.
 Objects are instances of a class.
 $this refers to the current object instance.
 Static members are accessed using ::.
 Visibility levels determine accessibility: public, private, protected.

3.2 CONSTRUCTOR AND DESTRUCTOR
Constructor
A constructor is a special method that is called automatically when an object is created from
a class. In PHP, we define a constructor using the __construct() method.
Corrected Example for Constructor:
<?php
class Student
{
public $roll_no;
public $name;

// Constructor
public function __construct()
{
$this->roll_no = 10;
$this->name = "Amar";
}

// Method to display values


public function display()
{
echo "Roll No: $this->roll_no <br>";
echo "Name: $this->name";
}
}

// Creating object
$s1 = new Student();
$s1->display();
?>
Output:
Roll No: 10
Name: Amar
Key Points about Constructors:
 A constructor is automatically executed when an object is created.
 It is used to initialize object properties.
 In PHP, the constructor method is always named __construct().

Constructor Overloading in PHP


PHP does not support constructor overloading (i.e., multiple constructors with different
parameters). However, we can simulate it using functions like func_get_args() and func_num_args().
Corrected Example for Constructor Overloading:
<?php
class BankAccount
{
private $accountNumber;
private $totalBalance;

// Constructor
public function __construct()
{
$args = func_get_args();
$num = func_num_args();
if (method_exists($this, 'init_'.$num))
{
call_user_func_array(array($this, 'init_'.$num), $args);
}
}

// Method for one argument


public function init_1($accountNo)
{
$this->accountNumber = $accountNo;
}

// Method for two arguments


public function init_2($accountNo, $initialAmount)
{
$this->accountNumber = $accountNo;
$this->totalBalance = $initialAmount;
}
}

// Creating objects
$a1 = new BankAccount("121412324", 20000);
var_dump($a1);

$a2 = new BankAccount("232321242");


var_dump($a2);
?>
Output:
object(BankAccount) [1]
private 'accountNumber' => string '121412324' (length=9)
private 'totalBalance' => int 20000

object(BankAccount) [2]
private 'accountNumber' => string '232321242' (length=9)
private 'totalBalance' => NULL
How Constructor Overloading Works?
 func_get_args() retrieves the arguments passed to the constructor.
 func_num_args() gets the number of arguments.
 method_exists($this, 'init_'.$num) checks if a method exists based on the number of
parameters.
 call_user_func_array() dynamically calls the appropriate init_X() method.

Destructor
A destructor is a special function that is called automatically when an object is destroyed or
goes out of scope. In PHP, we define a destructor using the __destruct() method.
Corrected Example for Destructor:
<?php
class Test
{
public function __construct()
{
echo "Constructor called...<br>";
}

public function __destruct()


{
echo "Destructor called...";
}
}
// Creating object
$obj = new Test();
?>
Output:
Constructor called...
Destructor called...
Key Points about Destructors:
1. The destructor cannot take arguments.
2. It is called when the object is no longer referenced or when the script execution ends.
3. Useful for cleaning up resources like closing files, database connections, etc.

Summary
Feature Constructor (__construct()) Destructor (__destruct())
When is it called? Automatically when object is created Automatically when object is destroyed
Purpose Initialize object properties Clean up resources
Can take arguments? ✅ Yes ❌ No
Overloading support? ❌ No, but can be simulated ❌ No

3.3 Inheritance
PHP supports inheritance, where a new class (child class) inherits properties and methods from
an existing class (parent class). The extends keyword is used for inheritance.
Example: Inheritance in PHP
<?php
class Person {
public $name;
public $age;
}

class Employee extends Person {


public $salary;
public $designation;
}

// Creating an Employee object


$obj_emp = new Employee();
$obj_emp->name = "John Doe";
$obj_emp->age = 30;
$obj_emp->salary = 50000;
$obj_emp->designation = "Manager";

// Creating a Person object


$obj_per = new Person();
$obj_per->name = "Alice";
$obj_per->age = 25;

// Allowed
echo $obj_emp->name . " - " . $obj_emp->age . " - " . $obj_emp->salary . " - " . $obj_emp-
>designation . "<br>";
echo $obj_per->name . " - " . $obj_per->age . "<br>";

// Not allowed (This will cause an error)


// echo $obj_per->salary;
?>

3.3.1 Method Overriding


Method overriding allows a child class to redefine a method from its parent class with the same
name and parameters.
Example: Method Overriding in PHP
<?php
class Base {
function show() {
echo "Display Base <br>";
}
}

class Derived extends Base {


function show() {
echo "Display Derived <br>";
}
}

$sob = new Derived();


$sob->show(); // Output: Display Derived
?>
To call the parent class method from the child class, we use parent::method_name().
<?php
class Base {
function show() {
echo "Display Base <br>";
}
}

class Derived extends Base {


function show() {
parent::show(); // Calls parent class method
echo "Display Derived <br>";
}
}

$sob = new Derived();


$sob->show();
// Output:
// Display Base
// Display Derived
?>
3.3.2 Function Overloading
PHP does not support function overloading like Java or C++. However, we can achieve similar
behavior using magic methods (__call).
Example: Simulating Function Overloading
<?php
class Demo {
function __call($name, $arguments) {
if ($name == "test") {
switch (count($arguments)) {
case 1:
echo "Function called with one argument: " . $arguments[0] . "<br>";
break;
case 2:
echo "Function called with two arguments: " . $arguments[0] . ", " . $arguments[1]
. "<br>";
break;
default:
echo "Function called with different number of arguments <br>";
break;
}
}
}
}

$obj = new Demo();


$obj->test("Hello");
$obj->test("Hello", "World");
?>

3.3.3 Object Cloning


PHP allows object cloning using the clone keyword. When cloning, the __clone() method (if
defined) is called.
Example: Object Cloning in PHP
<?php
class GFG {
public $data1;
public $data2;
public $data3;
}

$obj = new GFG();


$obj->data1 = "PHP";
$obj->data2 = "with";
$obj->data3 = "Web";

// Cloning the object


$copy = clone $obj;

// Modifying cloned object


$copy->data1 = "Computer";
$copy->data2 = "IT";
$copy->data3 = "Portal";

// Printing original and cloned object values


echo $obj->data1 . " " . $obj->data2 . " " . $obj->data3 . "<br>"; // PHP with Web
echo $copy->data1 . " " . $copy->data2 . " " . $copy->data3 . "<br>"; // Computer IT Portal
?>
3.4 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.
Advantages of Introspection
Introspection allows us to:
1. Obtain the name of the class to which an object belongs, as well as its member properties and
methods.
2. Write generic tools such as debuggers, serializers, and profilers.
PHP provides built-in functions for introspection, allowing us to examine classes, interfaces,
properties, and methods dynamically.

3.4.1 Examining Classes


PHP provides various functions to examine classes dynamically:
1. class_exists()
This function determines whether a class exists. It takes a string (class name) as input and
returns a Boolean value.
Syntax:
class_exists(classname);
 Returns TRUE if the class is defined, FALSE otherwise.
Example:
<?php
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
?>
Alternatively, we can use the get_declared_classes() function to retrieve an array of all declared
classes.
Example:
<?php
$classes = get_declared_classes();
print_r($classes);
?>

2. get_class_methods()
This function returns an array of all method names defined in a class.
Syntax:
$methods = get_class_methods(classname);
Example:
<?php
class MyClass {
function myMethod1() {}
function myMethod2() {}
}
$class_methods = get_class_methods('MyClass');
print_r($class_methods);
?>
Output:
Array ( [0] => myMethod1 [1] => myMethod2 )

3. get_class_vars()
This function returns an associative array of class properties (default values).
Syntax:
$properties = get_class_vars(classname);
Example:
<?php
class MyClass {
var $var1;
var $var2 = 100;
}

$class_vars = get_class_vars('MyClass');
var_dump($class_vars);
?>
Output:
array(2) {
["var1"] => NULL
["var2"] => int(100)
}

4. get_parent_class()
This function returns the name of the parent class of a given class.
Syntax:
$superclass = get_parent_class(classname);
Example:
<?php
class ParentClass {}
class ChildClass extends ParentClass {}

echo get_parent_class('ChildClass'); // Output: ParentClass


?>

3.4.2 Examining an Object


Introspection functions in PHP also allow examining objects at runtime.
1. is_object()
Checks if a variable is an object.
Syntax:
$yes_no = is_object($var);
Example:
<?php
$obj = new stdClass();
echo is_object($obj) ? 'Yes' : 'No'; // Output: Yes
?>
2. get_class()
Returns the class name of an object.
Syntax:
$class_name = get_class($object);
Example:
<?php
class MyClass {}

$obj = new MyClass();


echo get_class($obj); // Output: MyClass
?>

3. get_object_vars()
Returns an associative array of object properties and their values.
Syntax:
$properties = get_object_vars($object);
Example:
<?php
class MyClass {
public $a = 1;
public $b = 2;
}

$obj = new MyClass();


print_r(get_object_vars($obj));
?>
Output:
Array ( [a] => 1 [b] => 2 )

4. method_exists()
Checks if a class method exists in an object.
Syntax:
$yes_no = method_exists($object, $method_name);
Example:
<?php
class MyClass {
function myMethod() {}
}

$obj = new MyClass();


echo method_exists($obj, 'myMethod') ? 'Method exists' : 'Method does not exist';
?>
Output:
Method exists
3.5 SERIALIZATION IN PHP
Serialization is the process of converting an object into a byte-stream representation that can
be stored in a file or transmitted over a network. This is useful for saving data persistently.
For example, PHP sessions automatically save and restore objects. We can manually serialize
and unserialize objects using the following functions:
 serialize($value) → Converts an object or value into a storable string.
 unserialize($string) → Recreates an object or value from a serialized string.
Example Usage
$sencoded = serialize($somedata);
$somedata = unserialize($sencoded);
Syntax
string serialize(mixed $value)
mixed unserialize(string $string)
Object Serialization in PHP
When serializing an object:
 All variables (properties) are saved.
 Functions (methods) are not saved.
 The serialized string can be stored in a file.
 To unserialize an object in another PHP file, the class definition must be included in
that file.
Example: Serializing and Storing an Object
<?php
class Student {
var $age = 10;

function showAge() {
echo $this->age;
}
}

// Create an object
$stud = new Student;
$stud->showAge(); // Outputs: 10

// Serialize the object


$sri_obj = serialize($stud);

// Save serialized object into a file


$fp = fopen("student.txt", "w");
fwrite($fp, $sri_obj);
fclose($fp);

// Unserialize the object


$us_obj = unserialize($sri_obj);
$us_obj->showAge(); // Outputs: 10
?>
__sleep() and __wakeup() Functions
PHP provides two magic methods to manage object serialization:
1. __sleep()
o Called before serialization.
o Can be used to clean up resources.
o Returns an array of property names to serialize.
2. __wakeup()
o Called after unserialization.
o Can be used to reinitialize resources.
Example: Using __sleep() and __wakeup()
<?php
class Customer {
private $name;
private $credit_card_no;

public function __construct($name, $credit_card_no) {


$this->name = $name;
$this->credit_card_no = $credit_card_no;
}

public function __sleep() {


echo "Sleep calling <br>";
return array('name', 'credit_card_no'); // Only these properties will be serialized
}

public function __wakeup() {


echo "Wakeup calling <br>";
}
}

$c = new Customer("Amar", 1234567890);


$data = serialize($c);
echo $data . "<br>";

print_r(unserialize($data));
?>
Output:
Sleep calling
O:8:"Customer":2:{s:14:"Customername";s:4:"Amar";s:24:"Customercredit_card_no";i:1234
567890;}
Wakeup calling
Customer Object ([name:Customer:private] => Amar [credit_card_no:Customer:private] =>
1234567890)
Practise Questions:
1. What is Object-Oriented Programming (OOP)?
2. Define an object in OOP.
3. What is a class? Give an example.
4. How does an object differ from a class?
5. Explain the concept of inheritance in OOP.
6. Describe method overloading and how it works with an example.
7. Write a PHP class named Car with properties like brand and model, and create
an object of this class.
8. Demonstrate how to serialize and unserialize an object in PHP.
9. Compare and contrast method overloading and method overriding.
10. Analyze the role of __sleep() and __wakeup() functions in PHP and explain
their practical use cases.
11. Evaluate the advantages and disadvantages of using OOP over procedural
programming in PHP.
12. Assess how inheritance improves code reusability in a large software project.
13. Design a PHP class hierarchy where a Vehicle class is the parent, and Car and
Bike are child classes with their unique properties and methods.
14. Develop a PHP script that demonstrates polymorphism by creating multiple
classes with a common interface.

You might also like