0% found this document useful (0 votes)
15 views11 pages

UNIT 4php

This document provides an overview of classes and objects in PHP, detailing how classes encapsulate data and behavior, support inheritance, and utilize visibility modifiers. It explains the concepts of constructors and destructors, method overloading, and inheritance, emphasizing the importance of these features for code organization and reusability. Examples illustrate how to define classes, create objects, and implement constructors and destructors in PHP.

Uploaded by

sonuaishu47
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)
15 views11 pages

UNIT 4php

This document provides an overview of classes and objects in PHP, detailing how classes encapsulate data and behavior, support inheritance, and utilize visibility modifiers. It explains the concepts of constructors and destructors, method overloading, and inheritance, emphasizing the importance of these features for code organization and reusability. Examples illustrate how to define classes, create objects, and implement constructors and destructors in PHP.

Uploaded by

sonuaishu47
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/ 11

UNIT 4

CLASSES AND OBJECTS


4.1 Classes
 In PHP, classes are fundamental constructs used to create objects, which are
instances of those classes.
 A class in PHP encapsulates both data (in the form of properties or variables)
and behaviour (in the form of methods or functions). This encapsulation helps
organize code logically and promotes reusability.
 Classes support the object-oriented paradigm by facilitating concepts like
inheritance, where classes can inherit properties and methods from parent
classes, and encapsulation, which restricts direct access to data from outside
the class.
 PHP classes also support visibility modifiers (public, private, protected) to
control access to class members, along with features like constructors (for
initializing objects) and destructors (for cleanup tasks).
 Overall, PHP classes provide a structured way to define and instantiate
objects, making code more modular, maintainable, and scalable.
4.1.1 Defining Class:
 To define a class, PHP has a keyword "class". Similarly, PHP provides the
keyword "new" to declare an object of any given class.
 The general form for defining a new class in PHP is as follows :
<?php
class phpClass {
var $var1;// or we can use public, protected, private
var $var2 = "constant string";

function myfunc ($arg1, $arg2) {


[..]
}
[..]
}
?>

 The keyword class is followed by the name of the class that you want to
Department of BCA, SRNMNCPage 1
define. Class name follows the same naming conventions as used for a PHP
variable. It is followed by a pair of braces enclosing any number of variable
declarations (properties) and function definitions.
 Variable declarations start with reserved keyword 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. Functions inside a
class are also called methods.
 In PHP, instead of the var keyword (which is now considered deprecated), you
should use visibility modifiers to define properties within a class. The three
primary visibility modifiers are public, protected, and private.
Example:

class Student {
public $name;
public $age;

public function read($name, $age) {


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

public function display() {


echo "Hello, my name is $this->name and I am $this->age
years old.";
}
}

This Keyword:
 The this keyword in PHP is used within a class to refer to the current instance
of the class, enabling access to the class's properties and methods from
within its own methods.
 It allows you to distinguish between class-level (static) and instance-level
Department of BCA, SRNMNCPage 2
(non-static) members, ensuring that the properties and methods accessed
belong to the specific object instance.
 This keyword is essential for maintaining context, as it differentiates between
the current object's properties and those of other instances or the class itself.
By using this, you enhance the readability and maintainability of your code,
clearly indicating that certain properties and methods are part of the current
object instance.
4.1.2 Visibility Modifiers:
In PHP, classes use visibility modifiers to control the accessibility of their
properties and methods. There are three visibility modifiers:
1. Public:
 Properties and methods declared as public can be accessed
from anywhere, including from outside the class, within the
class itself, and by child classes.
 Public properties and methods are typically used for class
components that need to be accessible or modifiable from
outside the class. For instance, public methods can serve as
interfaces to manipulate private or protected data within the
class.
2. Protected:
 Properties and methods declared as protected can be accessed
within the class itself and by any subclass that extends the
parent class. They are not accessible from outside the class
hierarchy.
 Protected properties and methods allow subclasses to interact
with the parent class’s internals while preventing external
access. This facilitates a controlled inheritance structure.
3. Private:
 Properties and methods declared as private can only be
accessed within the class that defines them. They are not
accessible from outside the class or by any subclass.
 Private properties and methods encapsulate data and behavior
that should not be exposed or altered by external entities,
including subclasses. This is ideal for sensitive data or internal
Department of BCA, SRNMNCPage 3
logic requiring strict control.

4.2 Objects
 An Object is an individual instance of the data structure defined by a class.
We define a class once and then make many objects that belong to it. Objects
are also known as instances.
 When a class is defined, it acts as a blueprint for creating multiple objects
that share the same properties and behaviours but hold their own individual
states.
 For example, consider a class Student that includes attributes such as name,
age, and student ID, and methods like enroll() and displayDetails(). Each
object created from this class represents an individual student with unique
values for these attributes. For instance, one Student object might have the
name "Alice", age 20, and student ID "S123", while another might be "Bob", age
22, and student ID "S124".
 These objects encapsulate data and functions, enabling modularity and reuse
in programming. As such, objects are also known as instances, highlighting
their role as concrete manifestations of the abstract class definition.
 The syntax for creating objects is as follows:

Objectname=new classname();.
 In PHP, creating an object from a class involves calling the class constructor
using the new keyword, which allocates memory for the object and initializes
its variables..
 Each object instantiated from a class operates independently, allowing
multiple instances to coexist with their own unique states and behaviours.
 An object is a data type that can store data and functions together in a single
unit. Objects are created using the new keyword followed by the class name.
Once an object is created, you can access its properties and methods using
the arrow notation (->).
 A class can have properties, which are variables that store data, and methods,
which are functions that perform actions on the object. Classes can also have
constructors, which are special methods that are called when an object is
created, and destructors, which are special methods that are called when the
Department of BCA, SRNMNCPage 4
object is destroyed.

<?php
class Student {
public $name;
public $age;

public function read($name, $age) {


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

public function display() {


echo "Hello, my name is $this->name and I am $this->age years old.\n";
}
}

$student1 = new Student();


$student2 = new Student();

$student1->read("aaa", 20);
$student1->display();

$student2->read("bbb", 22);
$student2->display();
?>>

4.3 Constructors and Destructors:


4.3.1 Constructor
 As in most of the object-oriented languages, you can define a constructor
function in a class in PHP also. When you declare an object with the new
operator, its member variables are not assigned any value. The constructor
function is used to initialize every new object at the time of declaration.
Department of BCA, SRNMNCPage 5
 PHP provides a __construct() function that initializes an object.
 The constructor method inside a class is called automatically on each newly
created object. Note that defining a constructor is not mandatory. However, if
present, it is suitable for any initialization that the object may need before it is
used.
 You can pass as many as arguments you like into the constructor function.
The __construct() function doesn’t have any return value.
<?php
class Student {
public $name;
public $regno;

public function __construct() {


$this->name = “ABB”;
$this->regno =”BCA123”;
}
public function displayDetails() {
echo "Name: " . $this->name . "<br>";
echo "Registration Number: " . $this->regno . "<br>";
}
}
$student = new Student();// this statement calls constructor
$student->displayDetails();
?>

Parameterized Constructor:
 A parameterized constructor in PHP is a special method called __construct
that initializes an object with parameters.
 When an object of a class is created, the constructor method is automatically
called, allowing you to set initial values for object properties.
Example
<?php
class Student {
public $name;
Department of BCA, SRNMNCPage 6
public $age;

function __construct($name, $age) {


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

public function display() {


echo "Hello, my name is $this->name and I am $this->age years old.\n";
}
}

$student1 = new Student();


$student2 = new Student();

$student1->read("aaa", 20);
$student1->display();

$student2->read("bbb", 22);
$student2->display();
?>>

4.3.2 Destructors:
 A destructor is called when the object is destructed or the script is stopped or
exited.
 If you create a __destruct() function, PHP will automatically call this function
at the end of the script.
Example:
<?php
Class student
{
public $name;
public $regno;
Department of BCA, SRNMNCPage 7
function __construct($name, $regno) {
$this->name = $name;
$this->regno = $age;
}
Function __destruct(){
echo “exiting script , destructing objects”;
}
}
$s=new student(“AAA”,”b123”);

4.4 Method overloading:


 Overloading is an Object-Oriented concept in which two or more methods
have the same method name with different arguments or parameters
(compulsory) and return type (not necessary).
 It can be done as Constructor Overloading, Operator Overloading, and Method
Overloading.
 Function overloading in PHP is used to dynamically create properties and
methods. These dynamic entities are processed by magic methods which can
be used in a class for various action types.
 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 function
__call(). This function takes function name and arguments.
 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.
Department of BCA, SRNMNCPage 8
 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.
 There are two 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.
o Setting and getting overloaded properties.
o Evaluating overloaded properties setting.
o Undo such properties setting.
 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,
o __call() – triggered while invoking overloaded methods in the object
context.
o __callStatic() – triggered while invoking overloaded methods in static
context.
o
Example:
<?php
class EG {
public function __call($name,
$arguments) {
echo "Calling object method
'$name' "
. implode(', ', $arguments). "\n";
}
public static function __callStatic($name,
$arguments) {
Department of BCA, SRNMNCPage 9
echo "Calling static method
'$name' "
. implode(', ', $arguments). "\n";
}
}
// Create new object
$obj = new EG;
$obj->runTest('in object context');
EG::runTest('in static context');
?>

4.5 Inheritace:
 Inheritance in object-oriented programming is a fundamental concept where
one class (the child or subclass) can inherit properties and methods from
another class (the parent or superclass).
 This relationship allows for the reuse of code, as the child class can access
and extend the behaviours defined in its parent class. Inheritance facilitates
the creation of hierarchical structures, where classes can be organized based
on their similarities and differences. The subclass inherits all non-private
members (properties and methods) from its superclass, enabling developers
to build upon existing functionality without needing to rewrite cod
 This principle promotes code reusability, modularity, and the efficient
management of complex systems by leveraging a structured and hierarchical
approach to software design.
 It is a concept of accessing the features of one class from another class. If
we inherit the class features into another class, we can access both class
properties. We can extends the features of a class by using 'extends' keyword.

 PHP supports only single inheritance, where only one class can be derived
from single parent class.

Example:

Department of BCA, SRNMNCPage 10


<?php
class demo
{
public function display()
{
echo "example of inheritance ";
}
}
class demo1 extends demo
{
public function view()
{
echo "in php";
}
}
$obj= new demo1();
$obj->display();
$obj->view();
?>
Output:
Example of inheritance in PHP

Department of BCA, SRNMNCPage 11

You might also like