TY CO PhP Unit 03
TY CO PhP Unit 03
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
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.
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";
function show() {
echo $this->publicVar . "<br>";
echo $this->privateVar . "<br>";
echo $this->protectedVar . "<br>";
}
}
// Constructor
public function __construct()
{
$this->roll_no = 10;
$this->name = "Amar";
}
// 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
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);
}
}
// Creating objects
$a1 = new BankAccount("121412324", 20000);
var_dump($a1);
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>";
}
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;
}
// Allowed
echo $obj_emp->name . " - " . $obj_emp->age . " - " . $obj_emp->salary . " - " . $obj_emp-
>designation . "<br>";
echo $obj_per->name . " - " . $obj_per->age . "<br>";
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 {}
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;
}
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() {}
}
function showAge() {
echo $this->age;
}
}
// Create an object
$stud = new Student;
$stud->showAge(); // Outputs: 10
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.