0% found this document useful (0 votes)
5 views22 pages

Class Objects

The document provides an overview of Object-Oriented Programming (OOP) in PHP, detailing its core principles: encapsulation, inheritance, polymorphism, and abstraction. It explains the benefits of OOP, including modularity, reusability, maintainability, scalability, flexibility, improved collaboration, real-world modeling, and robustness. Additionally, it covers the definitions and functionalities of classes, objects, properties, methods, constructors, destructors, and overloading in PHP.

Uploaded by

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

Class Objects

The document provides an overview of Object-Oriented Programming (OOP) in PHP, detailing its core principles: encapsulation, inheritance, polymorphism, and abstraction. It explains the benefits of OOP, including modularity, reusability, maintainability, scalability, flexibility, improved collaboration, real-world modeling, and robustness. Additionally, it covers the definitions and functionalities of classes, objects, properties, methods, constructors, destructors, and overloading in PHP.

Uploaded by

scriptsandbytes
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1 PHP>>unit3>>Classes_and_objects

Class &Objects in PHP

Object>>Oriented Programming (OOP) is a programming paradigm centered around the concept of objects, which
are instances of classes. "objects", which can contain data in the form of fields (often known as properties or
attributes) and code in the form of procedures (often known as methods).OOP organizes software design around
data, or objects, rather than functions and logic.

The Principles of Object>>Oriented Programming (OOP) are encapsulation, inheritance, polymorphism, and
abstraction. These properties define the core concepts and methodologies that OOP uses to organize and structure
software programs.

1. Encapsulation

Encapsulation is the concept of bundling the data (properties) and the methods (functions) that operate on the data
into a single unit or class. Encapsulation helps protect the data from unauthorized access and misuse by restricting
access to certain components. This is typically achieved using access modifiers:

>> Public: The property or method can be accessed from anywhere.

>> Protected: The property or method can be accessed within the class itself and by inheriting classes.

>> Private: The property or method can only be accessed within the class itself.

2. Inheritance

Inheritance is a mechanism by which one class (the child or subclass) can inherit properties and methods from
another class (the parent or superclass). This promotes code reuse and establishes a natural hierarchical relationship
between classes. Inheritance allows the child class to inherit the behavior and characteristics of the parent class
while also allowing the child class to introduce its own unique properties and methods.

3. Polymorphism

Polymorphism is the ability of different objects to be treated as instances of the same class through a common
interface. It allows one interface to be used for a general class of actions, with the specific action being determined
by the exact nature of the situation. Polymorphism is achieved through:

>> Method Overloading: Multiple methods with the same name but different parameters within the same class.

>> Method Overriding: A child class can provide a specific implementation of a method that is already defined in its
parent class.

4. Abstraction

Abstraction is the concept of hiding the complex implementation details and showing only the essential features of
an object. It focuses on what an object does instead of how it does it. Abstraction allows developers to manage
complexity by breaking down a system into smaller, more manageable parts. It provides a clear interface and
reduces the impact of changes to the underlying implementation.

HCES BCA COLLEGE GADAG


2 PHP>>unit3>>Classes_and_objects

Object>>Oriented Programming (OOP) Key Benefits:

1. Modularity

 Encapsulation: By bundling data and methods that operate on the data within objects, OOP helps create
modular code. Each class and object is a self>>contained module, which makes the code easier to manage,
understand, and debug.
 Separation of Concerns: Different parts of a program can be divided into distinct classes and objects, each with
its own responsibility, leading to a cleaner and more organized codebase.

2. Reusability

 Inheritance: Classes can inherit properties and methods from other classes, which promotes code reuse. Instead
of writing the same code multiple times, you can define common functionality in a base class and extend it in
derived classes.
 Class Libraries: OOP allows the creation of class libraries that can be reused across multiple projects, saving time
and effort.

3. Maintainability

 Ease of Updates: Encapsulation hides the internal state of objects from the outside, meaning that changes to the
internal implementation can be made without affecting other parts of the program.
 Code Readability: Well>>defined classes with clear interfaces make the code more readable and easier to
maintain. Developers can quickly understand the structure and flow of the program.

4. Scalability

 Extensibility: OOP makes it easier to extend the existing codebase. New functionality can be added by creating
new classes or extending existing ones without modifying the existing code.
 Manageability: Large applications can be broken down into smaller, more manageable pieces. Each class can be
developed, tested, and debugged independently.

5. Flexibility

 Polymorphism: Allows methods to do different things based on the object they are acting upon. This means you
can write more general and flexible code. For instance, you can write a function that can operate on objects of
different classes, as long as they implement a common interface.
 Dynamic Binding: Decisions about method implementation are made at runtime, which adds flexibility and
allows for more dynamic and adaptable code.

HCES BCA COLLEGE GADAG


3 PHP>>unit3>>Classes_and_objects

6. Improved Collaboration

 Team Development: OOP supports better project collaboration. Different team members can work on different
classes or objects simultaneously, without causing conflicts.
 Design Patterns: OOP encourages the use of design patterns, which are proven solutions to common problems.
This can improve the efficiency of the development process and lead to more robust and maintainable code.

7. Real>>World Modeling

 Natural Mapping: OOP concepts map more naturally to real>>world objects and relationships. This makes it
easier to conceptualize and design a system, as the objects in the program can represent real>>world entities.
 Intuitive Design: The paradigm encourages thinking in terms of objects and their interactions, which can be more
intuitive and aligned with how people perceive and describe the world.

8. Robustness

 Error Handling: Encapsulation and abstraction help in creating objects that are less prone to errors. Errors can be
localized and handled within objects, reducing the chances of cascading failures.
 Consistency: By using classes and objects, you can ensure consistency across the codebase. Once a class is tested
and verified, it can be reused reliably across the application

HCES BCA COLLEGE GADAG


4 PHP>>unit3>>Classes_and_objects

Class

In PHP, Classes are fundamental building blocks of object>>oriented programming (OOP) in PHP, enabling you to
create modular and maintainable code, a class is a blueprint or definition for creating objects. It encapsulates data
(properties) and associated functions (methods) that operate on that data, Classes promote code reusability by
allowing you to define a template for objects with similar characteristics and functionalities.

Objects

An object in programming is a fundamental unit of Object>>Oriented Programming (OOP) that represents a


real>>world entity, concept, or thing. It is an instance of a class, which serves as a blueprint or template for creating
objects. Objects encapsulate both data (in the form of properties or attributes) and behavior (in the form of methods
or functions) related to that entity.

Properties:

Properties are variables that define the characteristics or attributes of an object. They are declared within the class
definition and can be accessed and modified using the object instance.

Methods

Methods are functions defined within a class that operate on the object's data (properties). They can perform
actions, manipulate data, or interact with other objects. Methods are called using the object instance followed by
the dot notation (.) and the method name.

Defining a Class: You use the class keyword followed by the class name and curly braces {} to define a class. The class
name should start with a letter or underscore and can contain letters, numbers, and underscores.

Syntax:

class ClassName {

// Public property

public $propertyName;

// Protected property

protected $protectedProperty;

// Private property

private $privateProperty;

// Method with no parameters

public function methodName() {

// Method body

HCES BCA COLLEGE GADAG


5 PHP>>unit3>>Classes_and_objects

// Method with parameters

public function methodName($param1, $param2) {

// Method body

Class Definition (`class ClassName`):

>> This line declares the beginning of a class definition named `ClassName`.

>> A class serves as a blueprint or template for creating objects. It encapsulates properties (variables) and methods
(functions) that define the behavior and characteristics of the objects instantiated from it.

Class Properties:

1. Public Property (`public $propertyName`):

>> Declares a public property named `$propertyName`.

>> Public properties can be accessed and modified from outside the class.

2. Protected Property (`protected $protectedProperty`):

>> Declares a protected property named `$protectedProperty`.

>> Protected properties can be accessed and modified from within the class itself and by classes that inherit from
it.

3. Private Property (`private $privateProperty`):

>> Declares a private property named `$privateProperty`.

>> Private properties can only be accessed and modified from within the class itself.

Class Methods:

4. Method with No Parameters (`public function methodName()`):

>> Defines a public method named `methodName` with no parameters.

>> Methods are functions defined within a class that perform specific actions or operations.

>> Public methods can be called from outside the class.

HCES BCA COLLEGE GADAG


6 PHP>>unit3>>Classes_and_objects

5. Method with Parameters (`public function methodName($param1, $param2)`):

>> Defines a public method named `methodName` with two parameters (`$param1` and `$param2`).

>> This method accepts two parameters and can perform actions or operations based on these parameters.

>> Parameters allow methods to accept input data or arguments.

CONSTRUCTOR

A constructor in programming, specifically in the context of Object>>Oriented Programming (OOP), is a special


method or function within a class that is automatically called when an object of that class is created. Its primary
purpose is to initialize the newly created object, typically by setting initial values for its properties or performing any
necessary setup tasks.

Characteristics of Constructors:

1. Initialization: The constructor initializes the state of the object by assigning initial values to its properties or
performing other necessary setup operations.

2. Automatic Invocation: Constructors are automatically invoked when an object of the class is created using the
`new` keyword. There is no need to explicitly call the constructor.

3. Special Method Name: In many programming languages, including PHP, the constructor method is identified by a
special name. In PHP, the constructor method is named `__construct`.

4. Optional Parameters: Constructors can accept parameters, allowing for customization of object initialization based
on input values provided during object creation.

5. No Return Type: Constructors do not have a return type declaration. Their primary purpose is to initialize the
object, not to return a value.

Example: Consider a class `Car` with properties `make`, `model`, and `year`.

<?php

class Car {

// Properties

public $color;

public $model;

public $year;

// Constructor

public function __construct($color, $model, $year) {

HCES BCA COLLEGE GADAG


7 PHP>>unit3>>Classes_and_objects

// Initialize properties

$this->make = $color;

$this->model = $model;

$this->year = $year;

$obj=new Car(“red”, “BMW”, 2024);

echo $obj->model;

?>

In this example:

>> The `Car` class has a constructor `__construct` that accepts three parameters (`$make`, `$model`, `$year`).

>> When an object of the `Car` class is created using the `new` keyword, the constructor is automatically invoked
with the provided arguments, and the object's properties are initialized accordingly.

DESTRUCTOR

A destructor, in the context of programming, particularly in Object-Oriented Programming (OOP), is a special method
within a class that is automatically called when an object is destroyed or goes out of scope. Its primary purpose is to
perform clean up tasks or release resources associated with the object before it is removed from memory.

Characteristics of Destructors:

1. Cleanup Operations: Destructors are used to perform cleanup operations such as closing files, releasing database
connections, freeing memory, or releasing any other resources acquired by the object during its lifetime.

2. Automatic Invocation: Destructors are automatically invoked when an object is destroyed or goes out of scope.
They are called implicitly by the system and do not require manual invocation.

3. Special Method Name: In many programming languages, including PHP, the destructor method is identified by a
special name. In PHP, the destructor method is named `__destruct`.

4. No Parameters: Destructors typically do not accept any parameters. They are invoked without any arguments
when the object is being destroyed.

5. No Return Type: Destructors do not have a return type declaration. Their primary purpose is to clean up
resources, not to return a value.

Example: Consider a class `FileHandler` that opens a file for reading. Here's how a destructor might be defined in PHP
to close the file when the object is destroyed:

HCES BCA COLLEGE GADAG


8 PHP>>unit3>>Classes_and_objects

<?php

class FileHandler {

// Properties

private $file;

// Constructor

public function __construct($filename) {

// Open the file

$this->file = fopen($filename, 'r');

// Destructor

public function __destruct() {

// Close the file

if ($this->file) {

fclose($this->file);

}?>

In this example:

- The `FileHandler` class has a constructor `__construct` that opens a file for reading and assigns the file handle to
the property `$file`.

- The `FileHandler` class also has a destructor `__destruct` that is automatically invoked when the object is
destroyed. It closes the file by calling the `fclose` function if the file handle exists.

OVERLOADING

HCES BCA COLLEGE GADAG


9 PHP>>unit3>>Classes_and_objects

In Object-Oriented Programming (OOP), overloading refers to the ability to define multiple methods or constructors
with the same name but different parameters within a class. This concept allows the same method or constructor
name to behave differently depending on the number or type of arguments passed to it. Overloading can enhance
code readability, flexibility, and reusability by providing a convenient way to handle different cases within a single
method or constructor.

Types of Overloading:

1. Method Overloading: Method overloading involves defining multiple methods with the same name but different
parameter lists within a [Link] methods must have different parameter lists, which can differ in the number or
types of [Link] compiler or runtime environment determines which method to invoke based on the
arguments passed during method invocation.

2. Constructor Overloading: Constructor overloading involves defining multiple constructors with the same name but
different parameter lists within a [Link] allows objects to be initialized in different ways based on the arguments
provided during object [Link] must have different parameter lists, enabling the creation of objects
with varying initial states or configurations.

PHP doesn't support overloading for methods (functions within a class) in the traditional sense where you have
multiple methods with the same name but different numbers or types of arguments. However, PHP offers
alternative mechanisms to achieve some functionality similar to overloading:

[Link] Built-in Support: Unlike some other programming languages, PHP does not support method overloading by
default. You cannot define multiple methods with the same name but different parameter lists within the same
class.

2. Using Default Parameter Values: One way to achieve similar functionality is by using default parameter values in
PHP methods. You can define a method with optional parameters and then handle different cases based on the
number or type of arguments passed to the method.

<?php

class MyClass {

public function myMethod($param1, $param2 = null) {

if ($param2 === null) {

// Handle case when only one parameter is passed

} else {

// Handle case when both parameters are passed

HCES BCA COLLEGE GADAG


10 PHP>>unit3>>Classes_and_objects

?>

3. Using Variable-Length Argument Lists: Another approach is to use variable-length argument lists
(`func_get_args()` or `...$args`) and handle different parameter scenarios within the method.

<?php

class MyClass {

public function myMethod(...$args) {

if (count($args) == 1) {

// Handle case when only one argument is passed

} elseif (count($args) == 2) {

// Handle case when two arguments are passed

// Handle other cases as needed

?>

INHERITANCE

HCES BCA COLLEGE GADAG


11 PHP>>unit3>>Classes_and_objects

In Object-Oriented Programming (OOP), inheritance is a fundamental concept that allows a class (known as a
subclass or child class) to inherit properties and methods from another class (known as a superclass or parent class).
This enables the subclass to reuse code and behavior defined in the superclass, promoting code reuse, extensibility,
and modularity.

Features of Inheritance:

1. Superclass-Subclass Relationship:Inheritance establishes an "is-a" relationship between classes. A subclass "is-a"


type of its [Link] subclass inherits all properties and methods (except constructors and destructors)
from its superclass.
2. Code Reuse:Inheritance allows subclasses to reuse code and behavior defined in the superclass, reducing
redundancy and promoting modular and maintainable code.
3. Method Overriding: Subclasses can override inherited methods from the superclass by providing their own
[Link] overriding allows subclasses to customize or extend the behavior of inherited methods
to suit their specific needs.
4. Access Modifiers: Inherited properties and methods retain their access modifiers (public, protected, or private)
from the superclass. Subclasses can access public and protected members of the superclass but cannot access
private members directly.

Inheritance is a key principle of OOP that allows subclasses to inherit properties and methods from superclasses,
promoting code reuse and extensibility. It establishes a hierarchical relationship between classes, enabling the
creation of specialized subclasses that extend or customize the behavior of their superclass. Inheritance enhances
modularity, maintainability, and flexibility in object-oriented designs.

In PHP, inheritance is a core feature of Object-Oriented Programming (OOP) that allows a class to inherit properties
and methods from another class. PHP supports single inheritance, meaning a class can inherit from only one parent
class. However, PHP supports chaining inheritance, where a subclass can become a superclass for another class.

Syntax of Inheritance in PHP:

<?php

class ParentClass {

// Properties and methods

class ChildClass extends ParentClass {

// Properties and methods specific to ChildClass

}?>

 The `extends` keyword is used in PHP to establish inheritance between classes. It indicates that the `ChildClass`
inherits from the `ParentClass`.

HCES BCA COLLEGE GADAG


12 PHP>>unit3>>Classes_and_objects

 The `ChildClass` can access all public and protected properties and methods of the `ParentClass`.
 If a property or method in the `ParentClass` is declared as `protected`, it can be accessed by the `ChildClass`.
However, if it is declared as `private`, it cannot be accessed directly by the `ChildClass`.
 The `ChildClass` can override methods from the `ParentClass` by redefining them with the same name and
signature.
 In PHP, constructors and destructors are not inherited, but they can be called explicitly in the child class using
the `parent::__construct()` and `parent::__destruct()` methods.

Example of Inheritance in PHP:

<?php

class Animal {

public $name;

public function __construct($name) {

$this->name = $name;

public function makeSound() {

return "Animal {$this->name} makes a sound.";

class Dog extends Animal {

public function makeSound() {

return "Dog {$this->name} barks.";

// Creating instances

$animal = new Animal("Generic");

$dog = new Dog("Buddy");

// Method invocation

echo $animal->makeSound(); // Output: Animal Generic makes a sound.

echo $dog->makeSound(); // Output: Dog Buddy barks.

HCES BCA COLLEGE GADAG


13 PHP>>unit3>>Classes_and_objects

?>

PHP offers mainly three types of inheritance based on their functionality. These three types are as follows:

 Single Inheritance: Single inheritance is the most basic or fundamental type of inheritance offered by PHP.
There is only one base class and one sub/derived class in a single inheritance and the subclass is directly
inherited from the base class.

 Hierarchical Inheritance: As the name suggests, the hierarchical inheritance adopts a tree-like structure,
where multiple derived classes are inherited from the base class.

 Multilevel Inheritance: Multilevel inheritance is the third type of inheritance supported in PHP. It occurs at
different levels. Here, one base class is inherited by a derived class, then that derived class is inherited by
other derived classes, and so on.

Types of Inheritance in PHP

 Single Inheritance

Single inheritance is the most basic and simple inheritance type. As the name suggests, in a single inheritance, there
is only one base class and one sub or derived class. It directly inherits the subclass from the base class.

The following program illustrates single level inheritance in PHP:

<?php

class Jewellery {

var $cost = 10000;

public function printName($name) {

echo 'This is base class: Jewellery & name of jewellery is: ' . $name . PHP_EOL;

// derived class named "Necklace"

class Necklace extends Jewellery {

public function printName($name) {

HCES BCA COLLEGE GADAG


14 PHP>>unit3>>Classes_and_objects

echo 'This is child class: Necklace & name of jewellery is: ' . $name . PHP_EOL;

// this class can access

// data member of its parent class.

echo 'Price is: ' . $this->cost . PHP_EOL;

$f = new Jewellery();

$s = new Necklace();

$f->printName('Ring');

$s->printName('Necklace');

?>

 Multilevel Inheritance

Multilevel Inheritance is another type of inheritance that is found in PHP. Multilevel inheritance can also be
explained by a family tree. There is one base class. This base class can be inherited by. These subclasses (not every
subclass necessarily) act as base class and are further inherited by other subclasses. This is just like a family having
descendants over generations.

The following program illustrates multilevel inheritance in PHP:

<?php

HCES BCA COLLEGE GADAG


15 PHP>>unit3>>Classes_and_objects

// base class named "Jewellery"

class Jewellery {

public function totalCost() {

return ' total jewellery cost: 600000';

// derived class named "Necklace"

// inherited form class "Jewellery"

class Necklace extends Jewellery {

public function necklace() {

return ' necklace cost: 450000';

// derived class named "Pendant"

// inherited form class "Necklace"

class Pendant extends Necklace {

public function pendantCost() {

return ' pendant cost: 600000';

public function priceList() {

echo '1. ' .$this->totalCost() . PHP_EOL;

echo '2. ' .$this->necklace() . PHP_EOL;

echo '3. ' .$this->pendantCost() . PHP_EOL;

// creating object of

// the derived class

HCES BCA COLLEGE GADAG


16 PHP>>unit3>>Classes_and_objects

$obj = new Pendant();

$obj->priceList();

?>

 Hierarchical Inheritance

As the name suggests, hierarchical inheritance shows a tree-like structure. Many derived classes are directly
inherited from a base class. In this type of inheritance, more than one derived class shares the same parent class.

The following program illustrates hierarchical inheritance in PHP:

<?php

// base class named "Jewellery"

class Jewellery {

public function Jewellery() {

echo 'This class is Jewellery ' . PHP_EOL;

// derived class named "Necklace"

HCES BCA COLLEGE GADAG


17 PHP>>unit3>>Classes_and_objects

class Necklace extends Jewellery {

// derived class named "Bracelet"

class Bracelet extends Jewellery {

// creating objects of

// derived classes

// "Necklace" and "Bracelet"

$n = new Necklace();

$b = new Bracelet();

?>

Protected Access Modifier in PHP

As discussed earlier, protected members of a class can only be accessed within that class and by the derived classes
that inherit it. Even an instance of the derived class cannot access the protected member of its base class, outside of
that class. This means that the protected members can be accessed only by a derived class and the base class itself,
and not anywhere else in the program.

The following programs illustrate the accessibility of protected members in PHP:

<?php

// base class named "Jewellery"

class Jewellery {

public $cost = 10000;

// protected member function

// of the base class

protected function display() {

echo 'This is the base class.' . PHP_EOL;

HCES BCA COLLEGE GADAG


18 PHP>>unit3>>Classes_and_objects

// derived class named "Necklace"

class Necklace extends Jewellery {

public function show() {

echo 'This is the child class. ' . PHP_EOL;

// create an object of the derived class

$obj = new Necklace();

// call function of derived class

$obj->show();

// call "protected" function of base class

$obj->display(); // this will throw error

?>

In the above program, an instance of the derived class tries to call a protected member function of its base class
outside both of the classes. That’s why the program is throwing an error.

This issue can be solved using a public method. Since a protected member can be directly accessed inside the
derived class, so calling the protected member in a public method of the derived class makes it possible to achieve
the task of accessing the protected member indirectly.

The following program illustrates this:

<?php

// base class named "Jewellery"

class Jewellery {

public $cost = 10000;

// protected member function

HCES BCA COLLEGE GADAG


19 PHP>>unit3>>Classes_and_objects

// of the base class

protected function display() {

echo 'This is the base class.' . PHP_EOL;

// derived class named "Necklace"

class Necklace extends Jewellery {

public function show() {

echo 'This is the child class. ' . PHP_EOL;

// protected member function of the base class

// can be accessed in this derived class

$this->display();

// create an object of the derived class

$obj = new Necklace();

// call function of derived class

$obj->show();

?>

Overriding Inherited Methods in PHP

Function overriding is supported by inheritance in PHP. It can be observed when a derived class and base class both
contain a function having the same name. Both the functions should have the same number of arguments. The

HCES BCA COLLEGE GADAG


20 PHP>>unit3>>Classes_and_objects

derived class inherits the member functions and data members from its base class. So to override a certain
functionality, you perform function overriding.

The following program illustrates the concept of method overriding in PHP:

<?php

// base class named "base_class"

class base_class {

// "show" function of the base class

public function show() {

echo 'This is the base class.' . PHP_EOL;

// derived class named "derived_class"

class derived_class extends base_class {

// "show" function of the derived class

public function show() {

echo 'This is the derived class. ' . PHP_EOL;

// create an object of the derived class

$obj = new derived_class();

// will call the "show"

// function of the derived class

$obj->show();

?>

In the program above, both the base class (i.e. base_class) and the derived class (i.e. derived_class) have a function
called “show”. If an instance of the derived class calls the show() function, then PHP will call the show() function of

HCES BCA COLLEGE GADAG


21 PHP>>unit3>>Classes_and_objects

the derived call. This is because the derived_class overrides the show() of the base_class with its own show()
method. If an instance of the base class uses the show() method, then there will be no overriding of the method.

Final

In PHP, the `final` keyword is used to restrict inheritance and prevent overriding of methods and classes. When
applied to a class, it indicates that the class cannot be subclassed, meaning no other class can extend it. When
applied to a method within a class, it indicates that the method cannot be overridden by subclasses.

1. Final Classes:

When a class is declared as `final`, it cannot be subclassed. This means that no other class can extend it. This is useful
when you want to prevent further specialization or modification of a particular class.

<?php

final class FinalClass {

// Class implementation

// This will result in a fatal error

class SubClass extends FinalClass {

// Class implementation

?>

2. Final Methods:

When a method is declared as `final` within a class, it cannot be overridden by subclasses. This is useful when you
want to enforce a specific implementation of a method across all subclasses or when you want to prevent
modification of a method's behavior in subclasses.

<?php

class ParentClass {

final public function finalMethod() {

// Method implementation

}}

class ChildClass extends ParentClass {

HCES BCA COLLEGE GADAG


22 PHP>>unit3>>Classes_and_objects

// This will result in a fatal error

public function finalMethod() {

// Method implementation

?>

1. Use `final` classes when you want to prevent further subclassing and modification of the class.

2. Use `final` methods when you want to enforce a specific implementation of a method across all subclasses or
prevent modification of a method's behavior in subclasses.

3. Be cautious when using `final`, as it restricts the flexibility of your code and may hinder future extensibility. It
should be used judiciously based on the specific requirements and design goals of your application.

The `final` keyword in PHP is used to restrict inheritance and prevent method overriding. When applied to a class, it
indicates that the class cannot be subclassed. When applied to a method within a class, it indicates that the method
cannot be overridden by subclasses. `final` provides a way to enforce immutability and prevent further modification
of classes and methods, enhancing code stability and maintainability in certain scenarios.

HCES BCA COLLEGE GADAG

You might also like