Static Members, Namespaces and Autoloading in PHP Practice Questions with Solutions

Introduction

Static members, namespaces, and autoloading help organize PHP applications and manage reusable code. Static properties and methods belong to a class rather than individual objects. PHP Namespaces prevent naming conflicts, while autoloading automatically loads class files when needed. In this chapter, you will practise these concepts through practical PHP examples. Static Members, Namespaces and Autoloading in PHP Practice Questions with Solutions to help you to understand the concepts.

Question 1: Create a Static Method in PHP

Problem Statement

Create a class named Calculator with a static method add() that accepts two numbers and displays their sum. Call the method without creating an object.

PHP Solution

<?php

class Calculator {

    public static function add($a, $b) {
        echo "Sum: " . ($a + $b);
    }
}

Calculator::add(20, 30);

?>

Sample Output

Sum: 50

Explanation

  • The static keyword makes a method static.
  • A static method belongs to the class rather than an individual object.
  • The :: operator, called the scope resolution operator, is used to access static members.
  • We call the method using Calculator::add() without creating an object.

Concepts Covered

  • Static methods
  • static keyword
  • Scope resolution operator ::
  • Calling methods without objects

Question 2: Create a Static Property

Problem Statement

Create a class named Company with a static property $companyName. Display the company name directly using the class name.

PHP Solution

<?php

class Company {

    public static $companyName = "ABC Technologies";

}

echo "Company Name: " . Company::$companyName;

?>

Sample Output

Company Name: ABC Technologies

Explanation

A static property belongs to the class rather than a particular object.

To access a static property, use the class name followed by the :: operator and the $ property name.

Company::$companyName;

Notice that the dollar sign is included before the property name.

Concepts Covered

  • Static properties
  • Accessing static properties
  • Class-level data
  • Scope resolution operator

Question 3: Count Objects Using a Static Property

Problem Statement

Create a class named Student with a static property $studentCount. Every time a new student object is created, increase the count by one using the constructor. Display the total number of students.

PHP Solution

<?php

class Student {

    public static $studentCount = 0;

    public function __construct() {
        self::$studentCount++;
    }

}

$student1 = new Student();
$student2 = new Student();
$student3 = new Student();
$student4 = new Student();

echo "Total Students: " . Student::$studentCount;

?>

Sample Output

Total Students: 4

Explanation

  • $studentCount is a static property shared by all objects of the class.
  • The constructor runs whenever a new object is created.
  • self::$studentCount accesses the static property from inside the class.
  • Each new object increases the shared count by one.

The static property maintains one common count instead of storing a separate count for every student object.

Concepts Covered

  • Static properties
  • Constructors
  • self:: keyword
  • Shared class-level data

Question 4: Use Static Methods to Calculate Employee Salary

Problem Statement

Create a class named SalaryCalculator with a static method calculateAnnualSalary(). The method should accept a monthly salary and calculate the annual salary.

PHP Solution

<?php

class SalaryCalculator {

    public static function calculateAnnualSalary($monthlySalary) {

        $annualSalary = $monthlySalary * 12;

        echo "Annual Salary: Rs. " . $annualSalary;

    }

}

SalaryCalculator::calculateAnnualSalary(30000);

?>

Sample Output

Annual Salary: Rs. 360000

Explanation

The calculateAnnualSalary() method performs a calculation without needing object-specific data.

Since the method is static, we can call it directly through the class name.

The annual salary is calculated by multiplying the monthly salary by 12.

Concepts Covered

  • Static methods
  • Reusable calculations
  • Method parameters
  • Calling static methods

Question 5: Access Static Members Using self::

Problem Statement

Create a class named BankAccount with a static property $bankName and an instance property $accountHolder.

Create a method named displayDetails() that displays both values using self:: for the static property and $this for the instance property.

PHP Solution

<?php

class BankAccount {

    public static $bankName = "National Bank";

    public $accountHolder;

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

    public function displayDetails() {

        echo "Bank Name: " . self::$bankName;
        echo "\nAccount Holder: " . $this->accountHolder;

    }

}

$account = new BankAccount("Rahul");

$account->displayDetails();

?>

Sample Output

Bank Name: National Bank
Account Holder: Rahul

Explanation

This example demonstrates the difference between static and instance members.

  • self::$bankName accesses a static property belonging to the class.
  • $this->accountHolder accesses a property belonging to the current object.
  • The constructor assigns the account holder’s name to the object.

Remember:

  • Use self:: to access static members from within the class.
  • Use $this-> to access instance properties and methods.

Concepts Covered

  • Static and instance properties
  • self:: keyword
  • $this keyword
  • Constructors

Question 6: Create a Namespace in PHP

Problem Statement

Create a namespace named School and define a class named Student inside it. Create an object of this class and display a welcome message.

PHP Solution

<?php

namespace School;

class Student {

    public function displayMessage() {
        echo "Welcome to School Student Management System.";
    }

}

$student = new Student();

$student->displayMessage();

?>

Sample Output

Welcome to School Student Management System.

Explanation

A namespace organizes classes, interfaces, functions, and constants into a named group.

The following statement creates a namespace:

namespace School;

The Student class belongs to the School namespace.

Because the code is already inside that namespace, we can create its object using new Student().

PHP Namespaces are useful when large applications contain classes with the same name.

Concepts Covered

  • PHP Namespaces
  • namespace keyword
  • Organizing classes
  • Creating objects inside a namespace

Question 7: Use Two Classes with the Same Name in Different PHP Namespaces

Problem Statement

Create two namespaces named School and College. Define a class named Student inside both namespaces.

Create objects of both classes in the same PHP file and display their messages.

PHP Solution

<?php

namespace School {

    class Student {

        public function displayMessage() {
            echo "This is a School Student.";
        }

    }

}

namespace College {

    class Student {

        public function displayMessage() {
            echo "This is a College Student.";
        }

    }

}

namespace {

    $schoolStudent = new \School\Student();
    $collegeStudent = new \College\Student();

    $schoolStudent->displayMessage();

    echo "\n";

    $collegeStudent->displayMessage();

}

?>

Sample Output

This is a School Student.
This is a College Student.

Explanation

Both PHP namespaces contain a class named Student.

Normally, two classes with the same fully qualified name cannot be declared in one application. Namespaces allow classes with the same short name to exist in different groups.

  • \School\Student refers to the Student class inside the School namespace.
  • \College\Student refers to the Student class inside the College namespace.
  • The leading backslash indicates that the name starts from the global namespace.

This prevents class naming conflicts in large applications.

Concepts Covered

  • Multiple namespaces
  • Same class names in different PHP namespaces
  • Fully qualified class names
  • Namespace blocks

Question 8: Import a Namespace Using the use Keyword

Problem Statement

Create a namespace named School containing a class named Student.

In another namespace named College, import the School\Student class using the use keyword and create its object.

PHP Solution

<?php

namespace School {

    class Student {

        public function displayMessage() {
            echo "Student class imported successfully.";
        }

    }

}

namespace College {

    use School\Student;

    $student = new Student();

    $student->displayMessage();

}

?>

Sample Output

Student class imported successfully.

Explanation

The use keyword imports a class from another namespace.

use School\Student;

After importing the class, we can create its object using the shorter name:

$student = new Student();

Without importing it, we would need to use its fully qualified name:

$student = new \School\Student();

The use statement for importing a namespace class must appear at the beginning of the namespace block, before executable statements.

Concepts Covered

  • Namespace importing
  • use keyword
  • Short class names
  • Fully qualified names

Question 9: Create a Simple Autoloading System

Problem Statement

Create a PHP project with two separate class files:

  • Student.php containing a Student class.
  • Teacher.php containing a Teacher class.

Create an index.php file that uses spl_autoload_register() to load the required class files automatically.

PHP Solution

File 1: Student.php

<?php

class Student {

    public function displayMessage() {
        echo "Student class loaded successfully.";
    }

}

File 2: Teacher.php

<?php

class Teacher {

    public function displayMessage() {
        echo "Teacher class loaded successfully.";
    }

}

File 3: index.php

<?php

spl_autoload_register(function ($className) {

    require_once __DIR__ . "/" . $className . ".php";

});

$student = new Student();
$teacher = new Teacher();

$student->displayMessage();

echo "\n";

$teacher->displayMessage();

?>

Sample Output

Student class loaded successfully.
Teacher class loaded successfully.

Explanation

Autoloading automatically loads a class file when PHP encounters a class that has not been loaded yet.

The spl_autoload_register() function registers an autoloading function.

When PHP needs the Student class:

  1. The autoloading function receives the class name Student.
  2. It builds the file path Student.php.
  3. require_once loads the file.
  4. PHP can now create the Student object.

The same process happens for the Teacher class.

The __DIR__ constant provides the directory path of the current file.

For this example, all three files should be saved in the same folder.

Concepts Covered

  • Autoloading in PHP
  • spl_autoload_register()
  • require_once
  • __DIR__ constant
  • Multiple PHP files

Question 10: Build a Namespace-Based Autoloading System

Problem Statement

Create a small PHP project with the following structure:

Project/
│
├── index.php
│
└── App/
    │
    ├── Student.php
    │
    └── Teacher.php

Both classes should belong to the App namespace.

Use spl_autoload_register() to load the required class files automatically and display messages from both classes.

PHP Solution

File 1: App/Student.php

<?php

namespace App;

class Student {

    public function displayMessage() {
        echo "Student class loaded from App namespace.";
    }

}

File 2: App/Teacher.php

<?php

namespace App;

class Teacher {

    public function displayMessage() {
        echo "Teacher class loaded from App namespace.";
    }

}

File 3: index.php

<?php

spl_autoload_register(function ($className) {

    $file = __DIR__ . "/" . str_replace("\\", "/", $className) . ".php";

    if (file_exists($file)) {
        require_once $file;
    }

});

$student = new \App\Student();
$teacher = new \App\Teacher();

$student->displayMessage();

echo "\n";

$teacher->displayMessage();

?>

Sample Output

Student class loaded from App namespace.
Teacher class loaded from App namespace.

Explanation

This example combines namespaces and autoloading in PHP.

1. Namespace declaration

Both class files use:

namespace App;

This means their fully qualified class names are:

  • App\Student
  • App\Teacher

2. Register the autoloader

The spl_autoload_register() function registers a function that PHP calls when an unloaded class is needed.

3. Convert the namespace into a file path

str_replace("\\", "/", $className);

This replaces namespace separators with directory separators.

For example:

App\Student

becomes:

App/Student

4. Load the required file

The file_exists() function checks whether the class file exists. If it does, require_once loads it.

5. Create objects

When PHP encounters new \App\Student(), the autoloader loads App/Student.php. The same process applies to the Teacher class.

This is a basic example of class autoloading in PHP. Real projects often use Composer’s PSR-4 autoloading standard to manage class files.

Concepts Covered

  • PHP Namespaces
  • Autoloading in PHP
  • spl_autoload_register()
  • str_replace()
  • file_exists()
  • require_once
  • Project folder structure

Key Takeaways

  • Static properties and methods belong to a class rather than individual objects.
  • Use the static keyword to declare static members.
  • Use the :: operator to access static properties and methods.
  • Use self:: to access static members from within the class.
  • PHP Namespaces organize classes and help prevent naming conflicts.
  • Use the namespace keyword to declare a namespace.
  • Use the use keyword to import classes from another namespace.
  • A fully qualified class name includes the complete namespace.
  • Autoloading in php automatically loads class files when PHP needs them.
  • Use spl_autoload_register() to register a custom autoloading function.
  • Composer supports automatic class loading using the PSR-4 standard.

Frequently Asked Questions (FAQs)

1. What are static members in PHP?

Static members are properties and methods that belong to a class rather than individual objects. They can be accessed using the class name and the scope resolution operator.

2. What is the difference between static and non-static methods?

A static method belongs to the class and can be called without creating an object. A non-static method in PHP belongs to an object and is normally called through an instance.

3. What is the use of the self:: keyword in PHP?

The self:: keyword accesses static properties, static methods, and class constants from within the class where they are defined.

4. What is the scope resolution operator in PHP?

The :: operator is called the scope resolution operator. It is used to access static members, class constants, and members in certain inheritance-related situations.

5. What are namespaces in PHP?

PHP Namespaces organize classes, interfaces, functions, and constants into separate groups. They help prevent naming conflicts when applications contain similar names.

6. What is the use of the use keyword in PHP?

The use keyword imports a class, interface, or other supported namespaced element so that it can be referred to using a shorter name.

7. What is autoloading in PHP?

Autoloading is a feature that automatically loads a class file when PHP encounters a class that has not yet been loaded.

8. What is spl_autoload_register() in PHP?

spl_autoload_register() registers one or more autoloading functions. PHP calls these functions when it needs to load an undefined class, interface, or trait.

9. What is the difference between require and autoloading in PHP?

require explicitly loads a specified file. Autoloading loads class files automatically when PHP needs a class that has not already been loaded.

10. What is Composer autoloading in PHP?

Composer autoloading automatically loads PHP classes according to configured rules, commonly PSR-4. It reduces the need to write custom autoloading functions for every project.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top