Object-Oriented Programming
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;
}
}
// 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...";
}
?>
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";
?>
• 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:
?>
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");
}
// subclass of the above class
class Male extends Human {
protected $gender = "Male";
?>
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;
?>
• 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 {
?>
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 {
?>
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 {
?>
• 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;
?>
We can have as many child classes as we want, lets have another class:
<?php
// child class
class Motorcycle extends Vehicle {
?>
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
?>
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);
}
}
?>
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;
namespace MyNamespace2;
class MyClass {
// class definition goes here
}
class MyClass {
// class definition goes here
}
?>
<?php
namespace MyOtherNamespace;
use MyNamespace\MyClass;
class MyClass {
// class definition goes here
}
function myFunction() {
// function definition goes here
}
?>
<?php
namespace MyOtherNamespace;
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...";
}
?>