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.

				
					<?php 
    class ExampleClass {
 
    }
?>

				
			

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().

				
					<?php 
class MyClass 
{ 
    // Constructor
    public function __construct(){ 
        echo 'The class "' . __CLASS__ . '" has been instantiated!<br>'; 
    } 
      
} 

// 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().

				
					<?php 
class MyClass 
{ 
    // Destructor 
    public function __destruct(){ 
        echo 'The class "' . __CLASS__ . '" has been destroyed!'; 
    } 
      
} 

// Create a new object of the class
$obj = new MyClass; 
?>

				
			

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

				
					<?php
class Plant
{
    function Plant()
    {
        echo "This is a user-defined constructor for the Plant class.";
    }
 
    function __construct()
    {
        echo "This is the pre-defined constructor for the Plant class.";
    }
}
 
$obj = new Plant();
?>

				
			

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.

				
					<?php

class Vehicle
{
    public $make;
    public $model;
 
    function __construct($make, $model)
    {
        $this->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

				
					<?php
class Animal
{
    function __construct()
    {
        print "Animal class constructor.\n";
    }
}
 
class Dog extends Animal
{
    function __construct()
    {
        parent::__construct(); // Call the parent constructor
        print "Dog class constructor.\n";
    }
} 

$obj1 = new Animal();
$obj2 = new Dog();
?>

				
			

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

				
					<?php
class Item
{
    function __construct()
    {
        echo "In constructor, ";
        $this->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
ConstructorsDestructors
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

				
					<?php
class ParentClass
{
    function __destruct()
    {
        echo "Destructor of Parent Class\n";
    }
}

class ChildClass extends ParentClass
{
    function __destruct()
    {
        echo "Destructor of Child Class\n";
        parent::__destruct(); // Call parent destructor
    }
}

$obj = new ChildClass();
?>

				
			

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 SpecifierAccess from ClassAccess from SubclassAccess from Outside
PrivateYesNoNo
ProtectedYesYesNo
PublicYesYesYes

Example 1: Public Access Specifier

				
					<?php  
class Calculator
{  
    public $x = 100;  // public attributes
    public $y = 50;

    function add()
    {  
        echo $this->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

				
					<?php  
class Calculator
{  
    private $a = 75;  // private attributes
    private $b = 5;

    private function divide()  // private member function
    {  
        echo $this->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

				
					<?php 
class Calculator
{ 
    protected $x = 1000;  // protected attributes
    protected $y = 100;

    function divide() 
    { 
        echo $this->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

				
					<?php 
// Class ExampleOne 
class ExampleOne { 
    public function greet() { 
        echo "Hi"; 
    } 
} 
  
// Trait ExampleTrait 
trait ExampleTrait { 
    public function greetTrait() { 
        echo " World"; 
    } 
} 
  
class Combined extends ExampleOne { 
    use ExampleTrait; 
    public function finalGreeting() { 
        echo "\nWelcome to the PHP World!"; 
    }  
} 
  
$test = new Combined(); 
$test->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.

				
					<?php 
// Trait ExampleOne 
trait ExampleOne { 
    public function greet() { 
        echo "Hello"; 
    } 
} 
  
// Trait ExampleTwo 
trait ExampleTwo { 
    public function greetTwo() { 
        echo " World"; 
    } 
} 
  
class MultipleTraits { 
    use ExampleOne, ExampleTwo; 
    public function finalMessage() { 
        echo "\nPHP Multiple Traits Example"; 
    }  
} 
  
$test = new MultipleTraits(); 
$test->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

				
					<?php 
  
class FirstClass { 
    public function insideFirst() { 
        echo "This is Class A"; 
    } 
} 
  
interface SecondInterface { 
    public function insideSecond(); 
} 
  
class InheritanceExample extends FirstClass implements SecondInterface { 
  
    public function insideSecond() { 
        echo "\nThis is Interface B"; 
    } 
  
    public function inChildClass() { 
        echo "\nThis is the child class"; 
    } 
} 
  
$example = new InheritanceExample(); 
$example->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() FunctionThe 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 is false, meaning the constant is case-sensitive.

Example: Creating Constants Using define() Function

				
					<?php

// Creates a case-sensitive constant
define("GREETING", "Hello World");
echo GREETING . "\n";

// Creates a case-insensitive constant
define("WELCOME", "Hello Universe", true);
echo welcome;

?>

				
			

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

				
					<?php
const WEBSITE = 'MyWebsite';
echo WEBSITE;
?>

				
			

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

				
					<?php

define("MESSAGE", "PHP is Fun!");

function displayMessage() {
    echo MESSAGE;
}

echo MESSAGE . "\n";
displayMessage();

?>

				
			

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:

FeatureConstantsVariables
SyntaxDoes not use $Starts with $
ValueImmutable (cannot be changed)Mutable (can be changed)
Case SensitivityCase-sensitive by defaultCase-sensitive
Global ScopeAlways globalScope depends on where it’s defined (local or global)
Declaration Methoddefine() or constDeclared 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

				
					<?php 

// Abstract class example in PHP 
abstract class BaseClass 
{ 
    // Abstract method (must be implemented by child classes)
    abstract function showData(); 
      
    // Non-abstract method
    function display() 
    { 
        echo "Base class method"; 
    } 
} 
?>

				
			
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:

				
					<?php 

// Abstract class
abstract class ParentClass { 
    // Abstract method
    abstract function showData(); 
} 

// Derived class extending the abstract class
class ChildClass extends ParentClass { 
    function showData() { 
        echo "Child class method"; 
    } 
} 

// Trying to create an instance of abstract class will cause an error
// $obj = new ParentClass();  // This will result in an error

$obj1 = new ChildClass; 
$obj1->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:

				
					<?php 

// Abstract class
abstract class ParentClass { 
    function __construct() { 
        echo "Abstract class constructor"; 
    } 
    
    // Abstract method
    abstract function showData(); 
} 

// Child class that extends the abstract class
class ChildClass extends ParentClass { 
    function __construct() { 
        echo "\nChild class constructor"; 
    } 
    function showData() { 
        echo "\nChild class showData method"; 
    } 
} 

$obj = new ChildClass; 
$obj->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:

				
					<?php 

// Invalid abstract class in PHP
abstract class ParentClass { 
    // This will cause an error because an abstract method cannot have a body
    abstract function showData() { 
        echo "This will cause an error"; 
    } 
} 

?>

				
			

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:

				
					<?php  

interface ExampleInterface { 
   public function methodOne(); 
   public function methodTwo(); 
}  

?> 

				
			
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:

				
					<?php 

interface SimpleInterface { 
   public function methodOne(); 
   public function methodTwo(); 
} 

class MyClass implements SimpleInterface { 
   public function methodOne() {  
     echo "Method One executed.\n"; 
   }  
   public function methodTwo() {  
     echo "Method Two executed.\n"; 
   }  
} 

$obj = new MyClass; 
$obj->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.

Interface Inheritance Example:
				
					<?php  

interface FirstInterface { 
    public function functionOne(); 
} 

interface SecondInterface extends FirstInterface { 
    public function functionTwo(); 
} 

class MyClass implements SecondInterface { 
    public function functionOne() { 
        echo "Function One from First Interface\n"; 
    } 
    public function functionTwo() { 
        echo "Function Two from Second Interface\n"; 
    } 
} 

$obj = new MyClass; 
$obj->functionOne(); 
$obj->functionTwo(); 

?>

				
			

Output:

				
					Function One from First Interface
Function Two from Second Interface

				
			

Practical Example of Interface Implementation:

				
					<?php  

interface BasicInterface { 
    public function showMethod1(); 
    public function showMethod2(); 
} 

class DemoClass implements BasicInterface { 
    public function showMethod1() { 
        echo "showMethod1 called.\n"; 
    } 
    public function showMethod2() { 
        echo "showMethod2 called.\n"; 
    } 
}  

$instance = new DemoClass; 
$instance->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

				
					<?php 
/* Demonstrating the use of a static function as a counter */
  
class Counter { 
      
    static $count; 
      
    public static function incrementCount() { 
        return self::$count++; 
    } 
} 
  
Counter::$count = 1; 
  
for($i = 0; $i < 5; ++$i) { 
    echo 'The next count is: ' . Counter::incrementCount() . "\n"; 
} 
  
?>

				
			

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

				
					<?php 
/* Demonstrating static methods in PHP */
  
class NonStaticClass { 
      
    public function display($message = "Hello World") { 
        $this->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

				
					<?php 
namespace MyNamespace {

    // This is regular PHP code
    function hello() 
    {
        echo 'Hello, I am running from a namespace!';
    }
}
?>

				
			
Global Namespace Declaration

If the namespace is to be declared globally (i.e., without a specific name), it is done like this:

				
					<?php 
namespace {
    // Code in the global space
}
?>

				
			
Declaring Multiple Namespaces in a Single File

You can declare multiple namespaces within a single PHP file:

				
					<?php
namespace MyNamespace1 {
    // Code for the first namespace
}

namespace MyNamespace2 {
    // Code for the second namespace
}

namespace {
    // Code in the global namespace
}
?>

				
			

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

				
					<?php
namespace MyNamespace;

function hello() 
{
    echo 'Hello, I am running from a namespace!';
}

// This calls the function within the MyNamespace namespace
hello();

// Explicitly resolves to MyNamespace\hello
namespace\hello();
?>

				
			

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

				
					<?php
namespace MyNamespace;

require 'project/database/connection.php';

// Creating an alias for Project\Database\Connection
use Project\Database\Connection as Conn;

$connection = new Conn();

// Importing the Project\Database namespace with alias
use Project\Database as DB;

$connection = new DB\Connection();
?>

				
			
Dynamic Namespaces

Although you can dynamically include files in PHP, dynamic namespace importing is not supported.

Example: Dynamic Namespace Usage

				
					<?php
namespace OtherProject;

$title = 'geeks';

// This is valid PHP code
require 'project/blog/title/' . $title . '.php';

// This will cause an error (invalid dynamic namespace)
use Project\Blog\title\$title;
?>

				
			

Runtime Error:

				
					PHP Fatal error: Invalid namespace usage