Contents
PHP OOPs
PHP Classes
Like C++ and Java, PHP supports object-oriented programming (OOP). Classes in PHP are the blueprints for creating objects. One key difference between functions and classes is that a class can contain both data (properties/variables) and functions (methods) that define the behavior of an object.
A class is essentially a programmer-defined data type that includes local methods and properties. It serves as a collection of objects, each having specific attributes and behavior.
Syntax:
To define a class, start with the keyword class
followed by the name of the class.
Note: Classes are enclosed using curly braces {}
, similar to how functions are defined.
Below are examples illustrating the use of classes in PHP’s object-oriented programming:
Example 1: Constructor in PHP Class
A constructor is a special method that gets called automatically when an object of the class is created. In PHP, constructors are defined using __construct()
.
';
}
}
// Create a new object of the class
$obj = new MyClass;
?>
Output:
The class "MyClass" has been instantiated!
Example 2: Destructor in PHP Class
A destructor is another special method that is invoked automatically when an object is no longer in use or the script execution ends. In PHP, destructors are defined using __destruct()
.
Output:
The class "MyClass" has been destroyed!
PHP Variables
Constructors are special methods used for initial settings when new instances of a class are created. They play a key role in PHP’s object-oriented programming model introduced in PHP5. Constructors act as the blueprint for creating objects, initializing their properties, and defining their behavior. Once the object is initialized, the constructor is automatically called. In contrast, destructors handle object cleanup and are automatically invoked at the end of the script execution.
In this article, we’ll explore constructors and destructors, two important concepts in PHP’s object-oriented programming.
Both constructors and destructors are special member functions, with the primary difference being that destructors are preceded by a ~
(tilde) symbol.
Constructor Syntax:
__construct():
function __construct()
{
// Initialize the object and its properties
}
Destructor Syntax:
__destruct():
function __destruct()
{
// Cleanup code
}
Note: The constructor is defined in the public section of the class. It is responsible for setting the initial values of the class properties.
Types of Constructors:
1. Default Constructor: It has no parameters but can accept dynamic values during object creation.
2. Parameterized Constructor: This constructor accepts parameters and assigns them to class properties.
3. Copy Constructor: This accepts another object as an argument and initializes the new object from it.
Inheritance and Constructors:
Constructors are inherited by child classes. If a child class defines its own constructor, it will be called instead of the parent’s constructor.
Pre-defined vs. User-defined Constructor:
When a class contains both the pre-defined __construct()
and a user-defined constructor, __construct()
will act as the constructor while the user-defined one behaves like a regular method.
Example 1: Pre-defined Constructor in PHP Class
Output:
This is the pre-defined constructor for the Plant class.
Example 2: Parameterized Constructor
In this example, the constructor takes parameters and sets the object’s properties accordingly.
make = $make;
$this->model = $model;
}
function show_details()
{
echo "Make: " . $this->make . ", Model: " . $this->model . "\n";
}
}
$vehicle1 = new Vehicle("Toyota", "Corolla");
$vehicle1->show_details();
$vehicle2 = new Vehicle("Honda", "Civic");
$vehicle2->show_details();
?>
Output:
Make: Toyota, Model: Corolla
Make: Honda, Model: Civic
Inheritance and Constructors
If a child class has its own constructor, both the child’s and parent’s constructors will be called in order.
Example 3: Constructor in Parent and Child Classes
Output:
Animal class constructor.
Animal class constructor.
Dog class constructor.
Destructor in PHP
Destructors are used to clean up resources when an object is no longer needed. They are automatically called when the object goes out of scope or the script ends.
Example 4: Destructor
name = "Item Object";
}
function __destruct()
{
echo "destroying " . $this->name . "\n";
}
}
$obj = new Item();
?>
Output:
In constructor, destroying Item Object
Note: In cases of inheritance, if both the parent and child class have destructors, the destructor of the child class is executed first, followed by the parent’s destructor.
Advantages of Constructors:
1. Automatic Initialization: Constructors allow automatic initialization of object properties when creating an instance.
2. Flexibility with Parameters: They can take multiple parameters, enabling dynamic initialization.
3. Reusability: Objects can be reused without having to reinitialize their properties each time.
4. Session Management: Constructors can initiate sessions, removing the need to start them manually in every function.
Destructor:
Destructors clean up resources and free memory before an object is destroyed. They are especially useful for closing file handles or database connections.
Constructor vs. Destructor Comparison
Constructors | Destructors |
---|---|
Accepts one or more parameters. | Takes no parameters. |
Named as __construct() . | Named as __destruct() . |
Called automatically when an object is created. | Called automatically when an object is destroyed. |
Used for initializing an object’s properties. | Used for cleaning up resources. |
Can be overloaded. | Cannot be overloaded. |
Allocates memory. | Deallocates memory. |
Example 5: Destructor in Inherited Class
Output:
Destructor of Child Class
Destructor of Parent Class
PHP Access Specifiers
In PHP, each property of a class must have one of three visibility levels, known as public, private, and protected.
Public: Public properties can be accessed by any code, whether that code is inside or outside the class. If a property is declared public, its value can be read or changed from anywhere in your script.
Private: Private properties of a class can be accessed only by code inside the class. If a property is declared private, only methods and objects inside the same class can access its contents.
Protected: Protected class properties are like private properties in that they can’t be accessed by code outside the class. However, classes that inherit from the parent class can access protected properties.
Generally, it’s recommended to avoid creating public properties wherever possible. Instead, it’s safer to create private properties and methods to control how external code interacts with class properties.
Note: Attempting to access a private or protected property outside the class results in a fatal error.
PHP Access Specifier Feasibility:
Access Specifier | Access from Class | Access from Subclass | Access from Outside |
---|---|---|---|
Private | Yes | No | No |
Protected | Yes | Yes | No |
Public | Yes | Yes | Yes |
Example 1: Public Access Specifier
x + $this->y;
echo " ";
}
}
class AdvancedCalculator extends Calculator
{
function subtract()
{
echo $this->x - $this->y;
}
}
$obj = new AdvancedCalculator();
// Accessing public properties and methods
$obj->add();
$obj->subtract();
?>
Output:
150 50
Example 2: Private Access Specifier
a / $this->b;
echo " ";
}
}
class AdvancedCalculator extends Calculator
{
function multiply()
{
echo $this->a * $this->b; // Trying to access private properties
}
}
$obj = new AdvancedCalculator();
// Attempting to access private method and properties
$obj->divide(); // This will cause a fatal error
$obj->multiply(); // This will cause a fatal error
?>
Output:
PHP Fatal error: Uncaught Error: Call to private method Calculator::divide() from context
Example 3: Protected Access Specifier
x / $this->y;
echo " ";
}
}
class AdvancedCalculator extends Calculator
{
function subtract()
{
echo $this->x - $this->y;
}
}
class OutsideClass
{
function multiply()
{
echo $this->x * $this->y; // Trying to access protected properties
}
}
$obj = new AdvancedCalculator();
// Accessing protected method from within the subclass
$obj->divide();
$obj->subtract();
// Trying to access protected properties from an external class
$obj2 = new OutsideClass();
$obj2->multiply(); // This will cause a fatal error
?>
Output:
10
900
Fatal error: Uncaught Error: Call to undefined method OutsideClass::multiply()
Multiple Inheritance in PHP
Multiple Inheritance refers to a feature in object-oriented programming languages where a child class can inherit properties and methods from multiple parent classes. PHP, by default, does not support multiple inheritance, but this can be achieved using Traits or Interfaces.
Using Traits for Multiple Inheritance
Traits allow you to reuse sets of methods across multiple classes. This makes it possible to mimic multiple inheritance in PHP.
Example 1: Using a Class and a Trait
greet();
$test->greetTrait();
$test->finalGreeting();
?>
Output:
Hi World
Welcome to the PHP World!
In this example, we use a class (ExampleOne
) and a trait (ExampleTrait
) in combination. The class Combined
inherits the method from both the parent class and the trait.
Example 2: Using Multiple Traits
You can include multiple traits in a class using the use
keyword.
greet();
$test->greetTwo();
$test->finalMessage();
?>
Output:
Hello World
PHP Multiple Traits Example
In this case, two traits (ExampleOne
and ExampleTwo
) are used together inside the MultipleTraits
class, allowing us to call methods from both traits.
Using Interfaces for Multiple Inheritance
PHP interfaces allow you to define methods that a class must implement, which enables multiple inheritance by implementing multiple interfaces.
Example 3: Using a Class and an Interface
insideFirst();
$example->insideSecond();
$example->inChildClass();
?>
Output:
This is Class A
This is Interface B
This is the child class
PHP Constants
Constants in PHP are identifiers or names assigned to fixed values that remain unchanged throughout the program execution. Once a constant is set, it cannot be redefined or removed.
By convention, constant names are written in uppercase. By default, constants are case-sensitive and must start with a letter or an underscore, followed by letters, numbers, or underscores. Special characters, except for the underscore, are not allowed.
1. Creating a Constant Using define()
Function: The define()
function is commonly used to create constants in PHP.
Syntax:
define('CONSTANT_NAME', value, case_insensitive);
name
: The name of the constant.value
: The value assigned to the constant.case_insensitive
: Defines whether the constant should be case-insensitive. The default value isfalse
, meaning the constant is case-sensitive.
Example: Creating Constants Using define()
Function
Output:
Hello World
Hello Universe
2. Creating a Constant Using const
Keyword: The const
keyword is another way to define constants, usually used within classes or functions. Unlike define()
, constants defined using const
are always case-sensitive.
Syntax:
const CONSTANT_NAME = value;
Example: Creating Constants Using const
Keyword
Output:
MyWebsite
3. Constants are Global: Constant global, meaning they can be accessed from any part of the script, including functions.
Example: Global Scope of Constants
Output:
PHP is Fun!
PHP is Fun!
In the example above, the constant MESSAGE
can be accessed both inside and outside the function displayMessage()
because constants have a global scope.
Difference Between Constants and Variables
Here are some key differences between constants and variables:
Feature | Constants | Variables |
---|---|---|
Syntax | Does not use $ | Starts with $ |
Value | Immutable (cannot be changed) | Mutable (can be changed) |
Case Sensitivity | Case-sensitive by default | Case-sensitive |
Global Scope | Always global | Scope depends on where it’s defined (local or global) |
Declaration Method | define() or const | Declared using $ symbol |
This updated content keeps the same meaning and structure but has revised wording and updated examples. The examples now reflect the typical usage of constants in PHP, and their respective outputs have been adjusted accordingly.
PHP Constants
Abstract Classes in PHP are classes where at least one method is declared as abstract. In PHP, abstract classes are defined using the abstract
keyword. The main purpose of abstract classes is that any class extending the abstract class must implement the abstract methods defined in the parent class. An abstract class can also contain non-abstract methods.
Syntax Example of an Abstract Class in PHP
Key Points About Abstract Classes in PHP:
1. Cannot Instantiate Abstract Classes: Like in Java, you cannot create an instance of an abstract class in PHP.
Example:
showData();
?>
Output:
Child class method
2. Abstract Classes Can Have Constructors: Similar to C++ or Java, abstract classes in PHP can contain constructors as well.
Example:
showData();
?>
Output:
Child class constructor
Child class showData method
3. Abstract Classes Must Contain At Least One Abstract Method: In PHP, unlike Java, you cannot create an abstract class without having at least one abstract method. If you try to define an abstract method with a body, PHP will generate a runtime error.
Example:
Runtime Error:
PHP Fatal error: Abstract function ParentClass::showData() cannot contain body
PHP Interface
Interface in PHP allows developers to define the structure of the methods that a class must implement without specifying the exact implementation. It serves as a way to enforce a contract for classes and provides a higher level of abstraction. Interfaces are similar to abstract classes but do not include any method bodies or data members. They ensure that any class implementing the interface must include the methods described.
Defining an Interface
To define an interface, we use the interface
keyword, similar to how we define a class, but without providing method implementations.
Syntax Example:
Key Features of Interfaces:
1. Abstract Methods: All methods in an interface are abstract, meaning they contain no method bodies.
2. Visibility Scope: Methods defined in interfaces must be public.
3. Multiple Implementations: A class can implement multiple interfaces, unlike inheritance where a class can only extend one parent class.
Implementing an Interface
To implement an interface in a class, use the implements
keyword. The class that implements the interface must provide implementations for all methods defined in the interface.
Example:
methodOne();
$obj->methodTwo();
?>
Output:
Method One executed.
Method Two executed.
Concrete Class:
A class that implements an interface is called a Concrete Class. It must provide implementations for all the methods defined by the interface. If two interfaces have the same method name, ambiguity may occur and cannot be implemented in the same class. An interface can extend another interface using the extends
keyword, just like class inheritance.
functionOne();
$obj->functionTwo();
?>
Output:
Function One from First Interface
Function Two from Second Interface
Practical Example of Interface Implementation:
showMethod1();
$instance->showMethod2();
?>
Output:
showMethod1 called.
showMethod2 called.
Benefits of Using PHP Interfaces
Unrelated Classes Can Share Methods:
Interfaces allow unrelated classes to implement the same set of methods, regardless of their inheritance hierarchy.Supports Multiple Inheritance:
A class can implement multiple interfaces, enabling a form of multiple inheritance, unlike classes that can only extend a single parent class.Focus on Interface, Not Implementation:
Interfaces allow the developer to focus on the interaction with an object rather than worrying about the actual implementation, maintaining consistency for the user of the interface.
Static Function in PHP
In certain scenarios, it is useful to access class methods and properties directly without the need to create an instance of the class. This can be achieved using the static
keyword. A method declared as static can be accessed without instantiating an object. Static methods are tied to the class itself, not a particular object instance. However, they can only interact with static properties and methods of the class.
To declare a static method, use the static
keyword as shown below:
public static function exampleMethod()
{
// Method logic here
}
Static methods can be invoked outside the class using the scope resolution operator ::
as follows:
MyClass::exampleMethod();
Example: Using a Static Method as a Counter
Output:
The next count is: 1
The next count is: 2
The next count is: 3
The next count is: 4
The next count is: 5
When to Use Static Methods?
The static
keyword is used in cases where variables and methods are common to all instances of a class. Any logic that needs to be shared across multiple instances should be placed in static methods. Static methods in PHP are often found in utility classes that contain shared functionality, such as those in frameworks like Laravel or CakePHP.
Below is an example demonstrating the use of static methods.
Example: Static Method in PHP
message = $message;
return $this->message;
}
}
class StaticClass {
public static function display($message) {
$message = "This is a static method";
return $message;
}
}
// Create an instance of NonStaticClass
$object = new NonStaticClass();
echo $object->display('This is a non-static method');
echo "\n";
echo StaticClass::display('This is non-static');
?>
Output:
This is a non-static method
This is a static method
PHP Namespace
Similar to C++, PHP namespaces provide a way to organize code and prevent name conflicts when reusing the same class, function, or constant names. Namespaces offer an abstract structure that lets you reuse names without encountering fatal errors due to naming conflicts.
Key points about namespaces in PHP:
- They serve as containers for your PHP code, allowing code reuse and preventing conflicts.
- Namespaces can include classes (including abstracts and traits), interfaces, functions, and constants.
- The
namespace
keyword is used to define a namespace. - It must be declared at the top of a file before any other code (except the
declare
keyword). - A namespace can hold valid PHP code, just like a regular PHP script.
Example: Declaring a Namespace
Global Namespace Declaration
If the namespace is to be declared globally (i.e., without a specific name), it is done like this:
Declaring Multiple Namespaces in a Single File
You can declare multiple namespaces within a single PHP file:
Namespaces are used to avoid conflicts and add flexibility and structure to your codebase. Just like directories in file systems, namespaces can be hierarchical. In PHP, the backslash (\
) serves as the namespace separator.
Example: Using a Namespace
Output:
Hello, I am running from a namespace!
Hello, I am running from a namespace!
Aliasing in Namespaces
Namespaces allow the use of aliases for ease of reference. The use
keyword imports namespaces, and you can use the as
keyword to create a custom alias.
Example: Aliasing in Namespaces
Dynamic Namespaces
Although you can dynamically include files in PHP, dynamic namespace importing is not supported.
Example: Dynamic Namespace Usage
Runtime Error:
PHP Fatal error: Invalid namespace usage