0% found this document useful (0 votes)
10 views69 pages

Object-Oriented Programming

The document provides an overview of Object-Oriented Programming (OOP) concepts in PHP, including classes, objects, properties, methods, encapsulation, inheritance, constructors, destructors, and access modifiers. It explains how to declare classes, create and access objects, and utilize access modifiers like public, private, and protected. Additionally, it covers the significance of constructors and destructors in initializing and cleaning up objects, as well as the principles of inheritance in OOP.

Uploaded by

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

Object-Oriented Programming

The document provides an overview of Object-Oriented Programming (OOP) concepts in PHP, including classes, objects, properties, methods, encapsulation, inheritance, constructors, destructors, and access modifiers. It explains how to declare classes, create and access objects, and utilize access modifiers like public, private, and protected. Additionally, it covers the significance of constructors and destructors in initializing and cleaning up objects, as well as the principles of inheritance in OOP.

Uploaded by

shikha sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 69

Object-Oriented Programming

Terminology
• When creating a program to use objects, you need to design a composite of
data and code called a class.
• Each new object based on this class is called an instance (or occurrence) of that
class.
• The data associated with an object is called its properties; the functions it uses
are called methods.
• In defining a class, you supply the names of its properties and the code for its
methods.
• When you’re creating objects, it is best to use encapsulation, or writing a class
in such a way that only its methods can be used to manipulate its properties.
• In other words, you deny outside code direct access to its data. The methods
you supply are known as the object’s interface.
• Once you have created a class, you may find that you need another class that is
similar to it but not quite the same. The quick and easy thing to do is to define a
new class using inheritance.
• When you do this, your new class has all the properties of the one it has
inherited from. The original class is now called the superclass, and the new one
is the subclass (or derived class).
Declaring a Class
• Before you can use an object, you must define a class with the class keyword.
Class definitions contain the class name (which is case-sensitive), its properties,
and its methods.
Example Declaring a class and examining an object
<?php
$object = new User;
print_r($object);
class User
{
public $name, $password;
function save_user()
{
echo "Save User code goes here";
}
}
?>
Here I have also used an invaluable function called print_r. It asks PHP to display
information about a variable in human-readable form. The _r stands for “in human
readable format.” In the case of the new object $object, it prints the following:
User Object
(
[name] =>
[password] =>
)
However, a browser compresses all the whitespace, so the output in a browser is
slightly harder to read:
User Object ( [name] => [password] => )
In any case, the output says that $object is a user-defined object that has the
properties name and password.
Creating an Object
To create an object with a specified class, use the new keyword, like this: object =
new Class. Here are a couple of ways in which we could do this:
$object = new User;
$temp = new User('name', 'password');
• On the first line, we simply assign an object to the User class. In the second, we pass
parameters to the call.
• A class may require or prohibit arguments; it may also allow arguments, but not require
them.
Accessing Objects
Example Creating and interacting with an object
<?php
$object = new User;
print_r($object); echo "<br>";
$object->name = "Joe";
$object->password = "mypass";
print_r($object); echo "<br>";
$object->save_user();
class User
{
public $name, $password;
function save_user()
{
echo "Save User code goes here";
}
}
?>
• As you can see, the syntax for accessing an object’s property is
$object->property.
• Likewise, you call a method like this: $object->method().
• You should note that the example property and method do not have $ signs in
front of them.
• If you were to preface them with $ signs, the code would not work, as it would
try to reference the value inside a variable.
• For example, the expression $object-> $property would attempt to look up the
value assigned to a variable named $property. If $property is undefined, an
attempt to reference $object->NULL would occur and cause an error.
PHP Constructor and Destructor
• When we create an object of any class, we need to set properties of that object
before using it.
• We can do that by first initialising the object and then setting values for the
properties, either by using the -> operator if the variables are public, or using
the public setter methods for the private variables.
• To create and initialize a class object in a single step, PHP provides a special
method called as Constructor, which is used to construct the object by assigning
the required property values while creating the object.
• And for destroying the object Destructor method is used.
Syntax for defining Constructor and Destructor
• In PHP, we have special functions to define constructor and destructor for a
class, they are: __construct() and __destruct().
<?php
class <CLASS_NAME> {

// constructor
function __construct() {
// initialize the object properties
}

// destructor
function __destruct() {
// clearing the object reference
}
}
?>
Constructor can accept arguments, whereas destructors won't have any argument
because a destructor's job is to detroy the current object reference.
PHP Constructor
Let's take the example of a class Person which has two properties, fname and lname,
for this class we will define a constructor for initialising the class properties(variables)
at the time of object creation.
<?php
class Person {
// first name of person
private $fname;
// last name of person
private $lname;

// Constructor
public function __construct($fname, $lname) {
echo "Initialising the object...<br/>";
$this->fname = $fname;
$this->lname = $lname;
}
// public method to show name
public function showName() {
echo "My name is: " . $this->fname . " " . $this->lname;
}
}

// creating class object


$john = new Person("John", "Wick");
$john->showName();
?>
• While earlier, we were using the -> operator to set value for the variables or
used the setter methods, in case of a constructor method, we can assign values
to the variables at the time of object creation.
• If a class has a constructor then whenever an object of that class is created, the
constructor is called.
PHP Constructor Overloading
• PHP doesn't support function overloading hence we cannot have multiple
implementations for constructor in a class.
PHP Destructor
• PHP Destructor method is called just before PHP is about to release any object from its
memory. Generally, you can close files, clean up resources etc in the destructor method.
Let's take an example,
<?php
class Person {
// first name of person
private $fname;
// last name of person
private $lname;

// Constructor
public function __construct($fname, $lname) {
echo "Initialising the object...<br/>";
$this->fname = $fname;
$this->lname = $lname;
}
// Destructor
public function __destruct(){
// clean up resources or do something else
echo "Destroying Object...";
}

// public method to show name


public function showName() {
echo "My name is: " . $this->fname . " " . $this->lname . "<br/>";
}
}

// creating class object


$john = new Person("John", "Wick");
$john->showName();

?>
If you see a PHP class with a function having same name as the name of the class,
then that function will act as the constructor. In older versions of PHP, constructor
was not defined using the __construct() name, but it used to have the same name
as the class name just like Core Java.
<?php
class Person {
// first name of person
private $fname;
// last name of person
private $lname;

// Constructor
public function Person($fname, $lname) {
echo "Initialising the object...<br/>";
$this->fname = $fname;
$this->lname = $lname;
}
// public method to show name
public function showName() {
echo "My name is: " . $this->fname . " " . $this->lname . "<br/>";
}
}
// creating class object
$john = new Person("John", "Wick");
$john->showName();
?>
PHP Access Modifiers
To set the access rights for class methods and variables we use access modifiers
which are nothing but PHP keywords. We can even assign some of these access
modifiers to the class itself to make the class behave in a special way.
Following are the PHP keywords which are used as access modifiers along with their
meaning:
• public: When we define class members as public, then they are accessible from
anywhere, even from outside of the class scope.
• private: When we define class members as private, they can only be accessed
from within the class itself.
• protected: This is same as private, with one exception, the class members
defined as protected can still be accessed from its subclass
• abstract: This keyword is only used for PHP classes and its member functions.
• final: The class methods defined as final, can not be changed or overriden by any
subclass.
When to use Which Access Modifier
We cannot use all the available access modifers with class, its varibales and
methods. In the table below, we have specified which access specifier is applied to
what:
Access Modifer classes functions variables
public Not Applicable Applicable Applicable
private Not Applicable Applicable Applicable
protected Not Applicable Applicable Applicable
abstract Applicable Applicable Not Applicable
final Applicable Applicable Not Applicable
public Access Modifier
• If we do not specify any access modifiers, all classes and its members are
treated as public by default.
• As mentioned in the table above, public, private or protected access modifiers
cannot be used with class. Let's see what happens if we do,
<?php
public class Student {
...
}
?>
Parse error: syntax error, unexpected 'public' (T_PUBLIC) in ...
But for class methods and variables we should specify the access specifiers
although by default they are treated as public.
This is a simple example of a PHP class:
<?php
class Student {
// to store name of person
public $name = “Ram Shrestha";

// simple class method


function display() {
echo “Welcome to class";
}
}
?>
private Access Modifier
We can use the private access modifier for class variables and methods but not for
PHP class. When a class member - a variable or a function, is declared
as private then it cannot be accessed directly using the object of the class. For
example:
<?php
class Person {
// first name of person
private $fname;
// last name of person
private $lname;

// public function to set value for fname


public function setFName($fname) {
$this->fname = $fname;
}
// public function to set value for lname
public function setLName($lname) {
$this->lname = $lname;
}
// public function to
public function showName() {
echo "My name is: " . $this->fname . " " . $this->lname;
}
}
// creating class object
$ram = new Person();

// trying to access private class variables


$ram->fname = “Ram"; // invalid
$shrestha->lname = “Shrestha"; // invalid

// calling the public function to set fname and lname


$ram->setFName(“Ram");
$shrestha->setLName(“Shrestha");

?>
• In the above code, $fname and $lname are private class variables, hence we
cannot directly access them using the class object.
• So, when we try to execute the following line of code:
<?php
$ram->setFName(“Ram");
?>
We will get a fatal PHP error:

Fatal error: Cannot access private property Person::$fname in ...


But we can easily access the private variables of a class by defining public functions in the class.
We can create separate functions to set value to private variables and to get their values too.
These functions are called Getters and Setters.
<?php
class Person {
// first name of person
private $name;

// public function to set value for name (setter method)


public function setName($name) {
$this->name = $name;
}

// public function to get value of name (getter method)


public function getName() {
return $this->name;
}
}
// creating class object
$ram = new Person();

// calling the public function to set fname


$ram->setName(“Ram Shrestha");

// getting the value of the name variable


echo "My name is " . $ram->getName();

?>
We should have getter and setter methods for all the private variables in the class.
protected Access Modifier
Just like the private access modifier, protected access modifer also restricts the access of class variables and
methods outside the class. But the protected class variables and functions can be accessed inside the class
and inside the subclass(a class that inherits the class).
<?php
class Human {
// protected variable
protected $genders = array("Male", "Female", "Other");

// protected function for humans features


protected function getFeatures($gender) {
if($gender == "Male") {
echo "Men";
}
else if($gender == "Female") {
echo "Women";
}
else if($gender == "Other") {
echo "All are born equal.";
}
}

}
// subclass of the above class
class Male extends Human {
protected $gender = "Male";

// public function to print Male features


public function getMaleFeatures() {
// calling the protected getFeatures() method of class Human
$this->getFeatures($this->gender);
}
}
// object of Human class
$human = new Human();
// object of Male class
$male = new Male();
/*
accessing protected variables and methods
*/
echo $human->genders; // INVALID
$human->getFeatures("Male"); // INVALID
echo $male->gender; // INVALID
/*
but we can call getMaleFeatures method,
in which we are calling a protected method
of Human class
*/
$male->getMaleFeatures();
?>
• In the program above, we have defined two classes, Human and Male. The
class Male is a subclass of the Human class.
• In the Human class all the class variables and methods are protected, hence they
cannot be accessed from outside the class, but they can be accessed inside the
subclass of the class Human.
abstract Access Modifier
• The abstract access modifier is used with PHP class and its functions. It cannot be
used for class variables.
• If a class has even a single abstract method. then the class must also be defined
as abstract.
• Also, PHP doesn't allow instantiating the abstract class i.e. you cannot create
object of an abstract class, although these classes can be inherited.
final Access Modifier
• When we declare a class as final, using this access modifier, then that class cannot
be inherited.
• Similarly, when we define a class function as final, PHP restricts the subclasses of
that class from overriding that function which is declared as final.
PHP Inheritance
• In object oriented programming, Inheritance enables a class to use properties and
methods of an existing class.
• Often while coding we come across situations where in we have to create a new
class with all the functionalities of an existing class and some additional methods,
more like an extension to an existing class, in such cases, we can either copy all
the properties and methods of the existing class into the new class to make them
available in the new class or we can simply inherit the old class in the new class.
• Consider a class Human with basic methods in it
like walk(), eat(), hear(), see() etc.
• Now if we have to create two more classes for male and female with
name Male and Female, with all the properties and methods of the
class Human and some specific features available only for Male and Female, we
can do so by inheriting Human class in Male and Female class.
• The class which is inherited is called Parent class(or super class or base class)
while the class which is inheriting other class is called as Child class(or sub class
or derived class).
• In the example above, Human will be the parent class and Male and Female will
be its child classes.
• A class can be inherited by multiple classes.
Syntax for Inheriting a Class
• In PHP, extends keyword is used to specify the name of the parent class while
defining the child class. For example,
<?php
class Human {
// parent class code
}

class Male extends Human {


// child class code
}

class Female extends Human {


// child class code
}
?>
Some important points to remember while using inheritance are:
• Child class can access and use only the non-private properties and methods on the parent
class.
• Child class can have it's own methods too, which will not be available to the parent class.
• Child class can also override a method defined in the parent class and provide its own
implementation for it.
<?php
// parent class
class Human {
// public property name
public $name;
// public function walk
public function walk() {
echo $this->name. " is walking...<br/>";
}
// public function see
public function see() {
echo $this->name. " is seeing...<br/>";
}
}
// child class
class Male extends Human {
// No code in child
}
// child class
class Female extends Human {
// No code in child
}
$male = new Male();
$male->name = "Adam";

$female = new Female();


$female->name = "Eve";

// calling Human class methods


// check the output (hehe, pun intended)
$female->walk();
$male->see();

?>
Child Class with its Own Methods and Properties
When a child class inherits a parent class, it can access and use all the non-private
members of the parent class. We know that, but can a child class has its own member
properties and methods? Yes, it can have. Let's take another example to see how we can do
this:
<?php
// parent class
class Vehicle {
// public property name
public $name;

// public function start


public function start() {
echo $this->name. " - Engine start...<br/>";
}

// public function stop


public function stop() {
echo $this->name. " - Engine stop...<br/>";
}
}
// child class
class Car extends Vehicle {

public function drive() {


echo "I am " . $this->name . "<br/>";
echo "Lets go on a drive...";
}
}
// child class
class Motorcycle extends Vehicle {
// motorcycle specific properties
// and methods
}
$car = new Car();
$car->name = "Mercedes benz";
// calling parent class method
$car->start();

// calling child class method


$car->drive();

?>
• When a class inherits another class, it gets an advantage of being able to use
the properties and methods defined in the parent class without again defining
them. And can also have its own properties and methods just like any other
normal class.
The protected Access Modifier
• When a child class inherits a parent class, it can only access and re-use the non-
private properties and methods. But we should not use public access modifiers
for the properties, as then the properties can be accessed from outside the
class too.
• To allow only the child class to access properties and methods of the parent
class, we can use the protected access modifier.
• When we define any property or method of a class as protected then those
properties and methods can only be accessed within the child class which
inherits the class.
<?php
// parent class
class Vehicle {
// protected property name
protected $name;
// public function start
public function start() {
echo $this->name. " - Engine start...<br/>";
}
// public function stop
public function stop() {
echo $this->name. " - Engine stop...<br/>";
}
}
// child class
class Car extends Vehicle {
public function drive() {
// accessing name variable of Car class
echo "I am " . $this->name . "<br/>";
echo "Lets go on a drive...";
}
}
$car = new Car();
$car->name = "Mercedes benz";
// calling parent class method
$car->start();
// calling child class method
$car->drive();
?>
In the example above we have made the name variable as protected, try running the same code with
name as private, you will get the error.
Overriding Parent class Method
What if a child class wants to use a parent class method but slightly differently? It can do so by
overriding the definition of the method defined in the parent class and provide its own definition.
This is known as Method Overriding.
<?php
// parent class
class Vehicle {
// public property name
public $name;
// public method
public function drive() {
echo "Vehicle class drive method...<br/>";
}
}
// child class
class Car extends Vehicle {
public function drive() {
echo "Car class drive method...<br/>";
}

}
// child class
class Motorcycle extends Vehicle {

public function drive() {


echo "Motorcycle class drive method...<br/>";
}
}
$car = new Car();
$car->name = "Mercedes benz";

// calling child class method


$car->drive();

$bike = new Motorcycle();


$bike->name = "Triumph Tiger";

// calling child class method


$bike->drive();

?>
In the code above, we have a parent class named Vehicle and two child classes
extending the parent class namely Car and Motorcycle. In the parent class we have
a method drive() which we have overriden in the child classes and have provided
different definition to it.
What if you do not want any child class to override the parent class method?
If we want so, we can define the method in the parent class as final.
Let's see what will happen if we will try to override a final method.
<?php
// parent class
class Vehicle {
// public property name
public $name;

// public method
final public function drive() {
echo "Vehicle class drive method...<br/>";
}
}
// child class
class Car extends Vehicle {

public function drive() {


echo "Car class drive method...<br/>";
}

$car = new Car();


$car->name = "Mercedes benz";

// calling child class method


$car->drive();

?>
OOP Constants
• PHP is a powerful, server-side scripting language that is widely used to create
dynamic web pages and applications.
• One of the core features of PHP is Object-Oriented Programming (OOP), which allows
developers to create complex and scalable applications.
What are Constants in PHP OOP?
• Constants in PHP are fixed values that cannot be changed during the execution of a
script.
• In OOP, constants are defined within a class and can be accessed using the class
name.
• Unlike variables, constants do not need to be declared with a dollar sign ($), and their
values cannot be changed once they have been set.
Defining Constants in PHP OOP
In PHP OOP, constants are defined using the const keyword, followed by the constant
name and its value. For example:
class MyClass {
const CONSTANT = 'constant value';
public function showConstant() {
echo self::CONSTANT . "\n";
}
}
In this example, we have defined a constant CONSTANT within the MyClass class
with a value of 'constant value'. The constant can be accessed using the class name
and the double colon (::) operator.
Accessing Constants in PHP OOP
Once a constant has been defined within a class, it can be accessed from within the
class or from outside the class. To access the constant from within the class, we use
the self keyword, followed by the double colon operator and the constant name.
To access the constant from outside the class, we use the class name, followed by
the double colon operator and the constant name. For example:
<?php
class MyClass {
const CONSTANT = 'constant value';
public function showConstant() {
echo self::CONSTANT . "\n";
}
}
echo MyClass::CONSTANT . "\n";
$class = new MyClass();
$class->showConstant();
In the first example, we have used the class name to access the constant. In the
second example, we have created an instance of the MyClass class and used the
object to access the constant.
Benefits of Using Constants in PHP OOP
There are several benefits to using constants in PHP OOP:
• Constants provide a way to store values that cannot be changed during the
execution of a script.
• Constants improve the readability of code by making it clear what values are
fixed and cannot be changed.
• Constants can be accessed from anywhere within a class or outside the class,
making it easy to reuse values across multiple parts of an application.
PHP Abstract Class and Methods
When can define a class abstract using the abstract keyword. An class which is
defined as abstract cannot be instantiated.
Following are some important points about abstract class and method:
• An abstract class can have methods and properties just like any other normal
class.
• An abstract class cannot be instantiated, hence we need to create a child class
which extends it, then we can create object of the child class.
• If a class has even a single abstract method then the class should also be
abstract.
• An abstract method is just the declaration, where we provide name of the
method and argument, while the body part is empty.
Creating an abstract Class
To declare a class abstract, we need to use the abstract keyword before the name
of the class.
<?php
// abstract class
abstract class Vehicle {

// abstract function mileage


abstract public function mileage();

?>
• In the example above, our class Vehicle is an abstract class, which has an
abstract method.
• The idea behind creating abstract class is to bound developers to follow a set of
guidelines, for example, if you want to create a new class which extends our
class Vehicle then you will have to provide definition for the abstract
method mileage(), else the child class should also be abstract. Hence, it is
mandatory for all the child classes to provide definition for the
method mileage().
Non Abstract Method in Abstract Class
• Any class with even a single abstract method must be declared abstract. But an
abstract class can have non-abstract methods as well, which can be accessed
and used directly by the child classes, without overriding them.
• Let's extend the example above, and include a non-abstract method in our
class Vehicle:
<?php
// abstract class
abstract class Vehicle {

// protected variable
protected $name;

// non-abstract public function start


public function start() {
echo $this->name. " - Engine start...<br/>";
}

// non-abstract public function stop


public function stop() {
echo $this->name. " - Engine stop...<br/>";
}
// non-abstract public function setName
public function setName($name) {
$this->name = $name;
}

// abstract function mileage


abstract public function mileage();
}
?>
Inheriting Abstract Classes
• Just like any other class, we can create classes extending abstract classes too.
• The only difference here is that the child class must provide definition for the
abstract method declared in the abstract parent class.
• If the child class doesn't provide definition for the abstract method, then it
should also be defined as an abstract class.
• Let's create two child classes inheriting the class Vehicle and which will have
definition for the abstract method mileage():
<?php
// child class
class Car extends Vehicle {

public function mileage() {


echo "I am " . $this->name . "<br/>";
echo "My mileage range is - 15 to 22 Km/L";
}

?>
We can have as many child classes as we want, lets have another class:
<?php

// child class
class Motorcycle extends Vehicle {

public function mileage() {


echo "I am " . $this->name . "<br/>";
echo "My mileage range is - 35 to 47 Km/L";
}

?>
As mentioned above that an abstract class cannot have any object, once we have
proper child classes defined, we can create object for them.
<?php

$car = new Car();


$car->setName("BMW X1");
$car->mileage();

?>
If you want to try, go ahead and try to create object of the class Vehicle, you will
get an error.
Object Oriented Programming with PHP Interfaces
• Interfaces are a fundamental part of Object Oriented Programming (OOP) in
PHP, and they play an important role in helping to ensure that code is well
organized, maintainable, and scalable.
Interface In PHP
• An interface in PHP is essentially a blueprint for a class. It defines a set of
methods and properties that must be implemented by any class that
implements the interface. This means that when you create a class that
implements an interface, you must provide implementations for all of the
methods and properties defined in that interface.
• This provides a level of structure and organization to your code, as you know
that any class that implements a particular interface will have the same basic
structure and functionality.
• This makes it easier to understand and maintain your code, as well as to add
new features and functionality in the future.
Why Use Interfaces in PHP?
• Interfaces are an important tool in PHP OOP because they provide a way to
ensure that your code is both organized and maintainable.
• They can also help you to enforce consistency and promote reusability, as you
can use the same interface in multiple classes, knowing that all of those classes
will have the same basic structure and functionality.
• Another advantage of using interfaces in PHP is that they allow you to define
contracts for your code. This means that you can define what a particular class
must do, without having to worry about how it will do it.
• This makes it easier to change and extend your code, as you can make changes
to the implementation of a particular class without affecting the rest of your
code.
Implementing Interfaces in PHP
• Implementing interfaces in PHP is simple and straightforward. To implement an
interface, you simply use the implements keyword in your class definition,
followed by the name of the interface. You can then provide implementations
for all of the methods and properties defined in the interface.
Here is an example of a class that implements a simple interface:
interface SimpleInterface {
public function hello();
}
class SimpleClass implements SimpleInterface {
public function hello() {
return 'Hello, World!';
}
}
In this example, the SimpleClass implements the SimpleInterface, and provides an
implementation for the hello() method.
• Interfaces are an important part of PHP OOP, and they play a crucial role in
helping to ensure that your code is well organized, maintainable, and scalable.
• By using interfaces, you can define contracts for your code, enforce consistency,
and promote reusability.
PHP OOP: Understanding Static Methods
• Static methods are a special type of method that are defined within a class and
can be called without creating an instance of the class.
• These methods belong to the class itself and not to any individual object of the
class.
What are Static Methods in PHP OOP?
• Static methods are methods that are defined using the static keyword. Once
defined, these methods can be called using the class name, without having to
create an instance of the class.
• Static methods are often used to perform operations that do not require access
to instance-specific data. For example, you may want to create a utility function
that performs a calculation, such as finding the average of a set of numbers.
Why use Static Methods in PHP OOP?
There are several reasons why you might want to use static methods in your PHP
OOP code:
• Performance - Since static methods do not require an instance of the class, they
can be executed faster than regular methods.
• Global Accessibility - Static methods can be called from anywhere in your code,
without having to create an instance of the class.
• Ease of Use - Static methods are easy to call, as they can be called using the
class name, rather than an instance of the class.
• Reusability - Static methods can be used by multiple classes, without having to
create an instance of each class.
How to Define and Call Static Methods in PHP OOP
Defining a static method in PHP OOP is easy. Simply add the static keyword before
the method name when defining the method within your class:
Once the static method has been defined, it can be called using the class name,
followed by the method name
<?php

class Math {
public static function average($numbers) {
return array_sum($numbers) / count($numbers);
}
}

$average = Math::average([1, 2, 3, 4, 5]);


echo $average;

?>
Understanding Static Properties in PHP OOP
• Static properties are properties that belong to the class itself, rather than to an
instance of the class.
• In other words, they are shared between all instances of a class. They are
accessed using the class name, rather than an instance of the class.
<?php
class User {
public static $count = 0;
public function __construct() {
self::$count++;
}
}
$user1 = new User();
$user2 = new User();
echo User::$count; // Outputs: 2
?>
• In the example above, we have created a User class with a static
property $count. Every time a new instance of the User class is created,
the $count property is incremented. Since the $count property is static, it is
shared between all instances of the User class and can be accessed using the
class name, User.
Why Use Static Properties in PHP OOP?
• Static properties are useful in certain situations where you need to store
information that is shared between all instances of a class. For example, you may
want to keep track of the total number of instances that have been created for a
particular class.
Namespace
• In PHP, use of namespaces allows classes / functions / constants of same name
be used in different contexts without any conflict, thereby encapsulating these
items.
• A namespace is logical grouping of classes/functions etc depending on their
relevence. Just as a file with same name can exist in two different folders, a
class of ertain name can be defined in two namespaces. Further, as we specify
the complete path of a file to gain access, we need to specify full name of class
along with namespace.
• Use of namespaces becomes crucial when application code grows. To give a
unique name to each class/function may become tedious and not exactly
elegant, namespace comes handy.
• For example, if we need to declare a calculate() function to calculate area as
well as tax, instead of defining them as something like calculate_area() and
calculate_tax(), we can create two namespaces area and tax and use calculate()
inside them.
Use of namespaces solves two problems.
• avoiding name collisions between classes/functions/constants defined by
someone with third-party classes/functions/constants.
• provides ability to alias (or shorten) Extra_Long_Names thereby improving
readability of source code.
PHP Namespaces provide a way in which to group related classes, interfaces,
functions and constants. Namespace names are case – insensitive
<?php
namespace myspace;
function hello() {
echo "Hello World";
}
?>
To call a function defined inside a namespace, include with use keyword. Name of
function is qualified with namespace
<?php
namespace myspace;
function hello() {
echo "Hello World";
}
use myspace;
myspace\hello(); ?>
Declaring a Namespace
• To declare a namespace in PHP, you use the namespace keyword followed by
the name of the namespace. The namespace declaration must be the first
statement in a PHP file, before any other code, including blank lines and
whitespace.
• Here is an example of declaring a namespace in PHP:
<?php
namespace MyNamespace;

// code goes here


?>
• In this example, we are declaring a namespace called MyNamespace. Any code
that follows the namespace declaration in this file will belong to
the MyNamespace namespace.
• If you have multiple namespaces in a single file, you can declare each
namespace separately, like this:
<?php
namespace MyNamespace1;

// code for MyNamespace1 goes here

namespace MyNamespace2;

// code for MyNamespace2 goes here


?>
Note that you can use any valid PHP identifier as a namespace name, including
underscores and backslashes. However, it is recommended to follow a consistent
naming convention for your namespaces, such as using the same naming
convention as your class names, to make your code easier to read and understand.
Using Namespaces
• Once you have declared a namespace in PHP, you can use it to organize your
code into logical groups. To use a namespace in your code, you simply prefix the
namespace name to the code item’s name, separated by a backslash ().
• For example, if you have a class called MyClass in a namespace
called MyNamespace, you can refer to that class using the fully qualified
<?php
namespace MyNamespace;

class MyClass {
// class definition goes here
}

// create an instance of MyClass


$obj = new MyNamespace\MyClass();
?>
In this example, we have defined a class called MyClass in
the MyNamespace namespace. To create an instance of this class, we use the fully
qualified name MyNamespace\MyClass to refer to it.
Importing Namespaces
• Importing namespaces in PHP allows you to refer to code items within that
namespace without having to specify the namespace prefix every time. You can
import a namespace using the use keyword followed by the fully qualified
namespace name.
<?php
namespace MyNamespace;

class MyClass {
// class definition goes here
}
?>
<?php
namespace MyOtherNamespace;

use MyNamespace\MyClass;

// create an instance of MyClass


$obj = new MyClass();
?>
In this example, we have defined a class called MyClass in
the MyNamespace namespace, and then imported that namespace into
the MyOtherNamespace namespace using the use keyword. This allows us to refer
to the MyClass class directly, without having to prefix it with
the MyNamespace namespace name.
You can also use the use keyword to import multiple code items from a namespace,
like this:
<?php
namespace MyNamespace;

class MyClass {
// class definition goes here
}

function myFunction() {
// function definition goes here
}
?>
<?php
namespace MyOtherNamespace;

use MyNamespace\{MyClass, myFunction};

// create an instance of MyClass


$obj = new MyClass();

// call the myFunction function


myFunction();
?>
• In this example, we have imported both the MyClass class and
the myFunction function from the MyNamespace namespace into
the MyOtherNamespace namespace, using the curly braces syntax.
• Importing namespaces in PHP provides a convenient and flexible way to manage
your code and make it easier to read and understand. By importing namespaces,
you can refer to code items within that namespace directly, without having to
specify the full namespace prefix every time.
Alias Namespaces
• In addition to importing namespaces in PHP, you can also create aliases for
namespaces using the as keyword. This allows you to refer to a namespace using
a different name, which can be useful for shortening long namespace names or
resolving naming conflicts.
• Here is an example of creating an alias for a namespace in PHP:
<?php
namespace MyVeryLongNamespaceName;
class MyClass {
// class definition goes here
}
?>
<?php
namespace MyOtherNamespace;
use MyVeryLongNamespaceName as VLN;
// create an instance of MyClass
$obj = new VLN\MyClass();
?>
• In this example, we have defined a class called MyClass in
the MyVeryLongNamespaceName namespace, and then created an alias for that
namespace called VLN using the as keyword. We then use the alias to refer to
the MyClass class, by prefixing it with VLN instead
of MyVeryLongNamespaceName.
• You can also create aliases for individual code items within a namespace, like
this:
<?php
namespace MyNamespace;
class VeryLongClassName {
// class definition goes here
}
?>
<?php
namespace MyOtherNamespace;
use MyNamespace\VeryLongClassName as ShortClass;
// create an instance of ShortClass
$obj = new ShortClass();
?>
Exception Handling
• With PHP 5 a new object oriented way of handling errors was introduced,
which is called Exception.
• Exception handling is used to handle errors and redirect the course of code
execution when it occurs, unlike errors where the code execution stops with an
error message displayed on the screen.
Using try and catch block
• The code which can lead to exception or error is enclosed within try block, if
no exception occur the code is executed normally while in case of exception,
the code execution exits the try block and enters the catch block.
• Following is the syntax for using try and catch for exception handling,
<?php
try {
//code goes here that could lead to an exception
}
catch (Exception $e) {
//exception handling code goes here
}
?>
throw Exception
• We can manually trigger an exception if required using
the throw keyword. Exception is a PHP class which is the parent class for all
exception classes in PHP.
• To throw an exception we have to create an object of the exception class and
then use the throw keyword to trigger that exception.
• Let's take an example:
<?php
// funciton declaration
function triggerException() {
// using throw keyword
throw new Exception("Manually triggering exception...");
}
?>
• If we call the above function triggerException() then it will throw exception.
• Now we can call this function from within a try block and handle the exception
in the catch() block, like this:
<?php

try {
// calling the function
triggerException();
}
catch (Exception $e) {
echo "Oops! Some unexpected error occured...";
}

?>
Inside the catch block, we can also get the message from the exception object using
the getMessage() method.
Custom Exception Class
We can create custom exception class by extending the Exception class provided by
PHP.
Below we have a an example for custom exception class:
<?php
// custom exception class
class CustomException extends Exception {
// define constructor
function __construct() {
// we can even take arguments if we want
}
// we can define class methods if required
}
?>
Custom exception classes are useful when you have requirements for custom error
handling, for example logging error in database etc.
Handling Multiple Exceptions
• If a piece of code can throw different types of exceptions and based on the type
of exception we have to perform some action, in such a situation we can have
multiple catch blocks:
<?php

try {
// calling the function
triggerException();
}
catch (CustomException $e) {
// do something here...
}
catch (Exception $e) {
echo "Oops! Some unexpected error occured...";
}

?>

You might also like