Introduction:
Explore the fundamentals of PHP Object-Oriented Programming (OOP)concept of static properties. Learn how static properties differ from instance properties, how to define and access them within classes that are by examples, projects and quiz
In PHP, static properties are properties of a class that belong to the class itself, rather than to any specific instance of the class. This means that the value of a static property is shared among all instances of that class.
Here’s an example showing the use of static properties in PHP:
class Counter { public static $count = 0; public function __construct() { // Increment the count each time a new instance is created self::$count++; } public static function getCount() { // Access the static property inside a static method using self:: return self::$count; } } // Create multiple instances of the Counter class $counter1 = new Counter(); $counter2 = new Counter(); $counter3 = new Counter(); // Accessing static property directly echo "Total count: " . Counter::$count . "\n"; // Output: 3 // Accessing static property via static method echo "Total count: " . Counter::getCount() . "\n"; // Output: 3
In this example:
Counter::$count is a static property shared among all instances of the Counter class.
self::$count is used inside the class to refer to the static property.
The getCount() method is declared as static and can be called without creating an instance of the class.
Static properties are useful when wewant to keep track of data that’s common to all instances of a class, such as a count of instances, or for storing configuration values that should be shared across all instances. However, they should be used with caution, as they can make code harder to test and reason about, especially in large applications with complex dependencies.
let’s go through a step-by-step guide on how to use static properties in PHP object-oriented programming (OOP):
we will Start by defining a class in PHP.
This class will contain static properties and methods.
class Counter { // Static property to keep track of count public static $count = 0; // Constructor public function __construct() { // Increment the count each time a new instance is created self::$count++; } // Static method to get the count public static function getCount() { return self::$count; } }
we can create instances of the class.
$counter1 = new Counter(); $counter2 = new Counter(); $counter3 = new Counter();
we can access the static property directly using the class name followed by :: operator.
echo "Total count: " . Counter::$count . "\n"; // Output: 3
Alternatively, we can define static methods in the class to access static properties.
echo "Total count: " . Counter::getCount() . "\n"; // Output: 3
we can also modify the static property.
Counter::$count = 10; // Set the count to 10 echo "Total count: " . Counter::getCount() . "\n"; // Output: 10
We’ve successfully used static properties in PHP OOP.
Static properties are useful when wewant to maintain data that is shared among all instances of a class, such as a count of instances or global configuration values.
Here’s a complete PHP code example embedded in a web page, showingthe use of PHP OOP with static properties.
We’ll provide explanations for each part of the code.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP OOP - Static Properties</title> </head> <body> <?php // Define a class with a static property and method class Counter { // Static property to keep track of count public static $count = 0; // Constructor public function __construct() { // Increment the count each time a new instance is created self::$count++; } // Static method to get the count public static function getCount() { return self::$count; } } // Create instances of the Counter class $counter1 = new Counter(); $counter2 = new Counter(); $counter3 = new Counter(); // Access static property directly using class name and :: operator echo "<p>Total count (accessing static property directly): " . Counter::$count . "</p>"; // Output: 3 // Access static property via static method echo "<p>Total count (accessing via static method): " . Counter::getCount() . "</p>"; // Output: 3 // Modify the static property Counter::$count = 10; // Set the count to 10 echo "<p>Modified total count: " . Counter::getCount() . "</p>"; // Output: 10 ?> </body> </html>
Explanation:
We define a class named Counter with a static property $count and a static method getCount().
Inside the constructor __construct(), we increment the static property $count every time a new instance of the Counter class is created.
We create three instances of the Counter class: $counter1, $counter2, and $counter3.
We then demonstrate two ways of accessing the static property $count: directly using the class name and :: operator (Counter::$count), and via the static method getCount() (Counter::getCount()).
Finally, we modify the static property $count to 10 and display the updated count using the static method getCount().
When we run this PHP script in a web server environment, it will display the total count of instances created using static properties and methods.
We will create a complete PHP project with an example showing the use of PHP OOP with static properties.
In this project, we’ll create a simple class called Product to represent products in an inventory system, and we’ll use a static property to keep track of the total number of products created.
Here’s the project structure:
project/
│
├── classes/
│ └── Product.php
│
└── index.php
Create a directory structure:
Create a directory named project. Inside the project directory, create another directory named classes.
Create the Product class:
Inside the classes directory, we will create a PHP file named Product.php.
This file will contain the Product class definition.
<?php class Product { // Static property to keep track of total products public static $totalCount = 0; // Properties of the product public $name; public $price; // Constructor public function __construct($name, $price) { $this->name = $name; $this->price = $price; // Increment the total count of products self::$totalCount++; } // Static method to get the total count of products public static function getTotalCount() { return self::$totalCount; } } ?>
In this class:
We have a static method getTotalCount() to retrieve the total count of products.
Create the index file:
Inside the project directory, we will create a PHP file named index.php.
This file will be the entry point of our project.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP OOP - Static Properties</title> </head> <body> <?php // Include the Product class include_once 'classes/Product.php'; // Create some products $product1 = new Product("Laptop", 999); $product2 = new Product("Smartphone", 699); $product3 = new Product("Tablet", 399); // Display total count of products echo "<p>Total number of products: " . Product::getTotalCount() . "</p>"; ?> </body> </html>
In this file:
We include the Product.php file to use the Product class.
We create three instances of the Product class.
We display the total count of products using the static method getTotalCount().
Run the project:
Now, we can run the index.php file in a web server environment.
It will display the total number of products created.
This project showsthe use of PHP OOP with static properties to keep track of shared data across all instances of a class. It’s a simple example, but it illustrates the concept effectively.
We will create another PHP project that utilizes static properties in an object-oriented manner. In this project, we’ll create a class called Employee to represent employees in a company, and we’ll use a static property to keep track of the next available employee ID.
Here’s the project structure:
employee_management/
│
├── classes/
│ └── Employee.php
│
└── index.php
Create a directory structure:
Create a directory named employee_management. Inside the employee_management directory, create another directory named classes.
Create the Employee class:
Inside the classes directory, we will create a PHP file named Employee.php.
This file will contain the Employee class definition.
<?php class Employee { // Static property to keep track of next available employee ID private static $nextId = 1; // Properties of the employee private $id; private $name; private $position; // Constructor public function __construct($name, $position) { $this->id = self::$nextId++; $this->name = $name; $this->position = $position; } // Method to get employee details public function getDetails() { return "ID: {$this->id}, Name: {$this->name}, Position: {$this->position}"; } } ?>
In this class:
Inside the employee_management directory,we will create a PHP file named index.php.
This file will be the entry point of our project.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Employee Management</title> </head> <body> <?php // Include the Employee class include_once 'classes/Employee.php'; // Create some employees $employee1 = new Employee("John Doe", "Manager"); $employee2 = new Employee("Jane Smith", "Developer"); $employee3 = new Employee("Mike Johnson", "Designer"); // Display employee details echo "<h2>Employee Details:</h2>"; echo "<ul>"; echo "<li>" . $employee1->getDetails() . "</li>"; echo "<li>" . $employee2->getDetails() . "</li>"; echo "<li>" . $employee3->getDetails() . "</li>"; echo "</ul>"; ?> </body> </html>
In this file:
Run the project:
Now, we can run the index.php file in a web server environment.
It will display the details of the employees along with their assigned IDs.
This project showsthe use of PHP OOP with static properties to manage shared data across instances of a class. The static property $nextId ensures that each employee is assigned a unique ID when created.
Let’s create another PHP project showingthe use of static properties in object-oriented programming. In this project, we’ll create a simple class called Book to represent books in a library, and we’ll use a static property to keep track of the total number of books available.
Here’s the project structure:
library_management/
│
├── classes/
│ └── Book.php
│
└── index.php
Create a directory structure:
Create a directory named library_management. Inside the library_management directory, create another directory named classes.
Create the Book class:
Inside the classes directory,we will create a PHP file named Book.php. This file will contain the Book class definition.
<?php class Book { // Static property to keep track of total number of books public static $totalCount = 0; // Properties of the book public $title; public $author; // Constructor public function __construct($title, $author) { $this->title = $title; $this->author = $author; // Increment the total count of books self::$totalCount++; } // Static method to get the total count of books public static function getTotalCount() { return self::$totalCount; } } ?>
In this class:
We define a class named Book with a public static property $totalCount to keep track of the total number of books.
We have two instance properties: $title and $author, representing the title and author of the book.
The constructor initializes the instance properties and increments the static property $totalCount.
We have a static method getTotalCount() to retrieve the total count of books.
Create the index file:
Inside the library_management directory,we will create a PHP file named index.php.
This file will be the entry point of our project.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Library Management</title> </head> <body> <?php // Include the Book class include_once 'classes/Book.php'; // Create some books $book1 = new Book("The Great Gatsby", "F. Scott Fitzgerald"); $book2 = new Book("To Kill a Mockingbird", "Harper Lee"); $book3 = new Book("1984", "George Orwell"); // Display total count of books echo "<p>Total number of books: " . Book::getTotalCount() . "</p>"; ?> </body> </html>
In this file:
We include the Book.php file to use the Book class.
We create three instances of the Book class.
We display the total count of books using the static method getTotalCount().
Run the project:
Now, we can run the index.php file in a web server environment. It will display the total number of books available in the library.
This project shows the use of PHP OOP with static properties to manage shared data across instances of a class. The static property $totalCount ensures that the total count of books is maintained accurately regardless of how many instances of the Book class are created.
Here’s a quiz about PHP OOP – Static Properties:
a) A property that can only be accessed within the class where it is defined
b) A property that belongs to a specific instance of a class
c) A property that belongs to the class itself, rather than to any specific instance
d) A property that is automatically initialized to null
Explanation:
c) Static properties in PHP OOP belong to the class itself, rather than to any specific instance of the class. They are shared among all instances of the class.
a) Using the $this keyword
b) Using the static keyword
c) Using the self keyword
d) Using the class name followed by :: operator
Explanation:
d) Static properties within a class can be accessed using the class name followed by :: operator, for example: ClassName::$propertyName.
a) public
b) static
c) var
d) staticProperty
Explanation:
b) The static keyword is used to define a static property in PHP.
a) When an object of the class is created
b) When the class is defined
c) When the property is explicitly assigned a value
d) When the property is accessed for the first time
Explanation:
b) A static property is initialized when the class is defined.
a) Only static methods
b) Only non-static methods
c) Both static and non-static methods
d) None of the above
Explanation:
c) Both static and non-static methods can access a static property.
a) It affects only that instance
b) It affects all instances of the class
c) It throws an error
d) It is not allowed
Explanation:
b) When a static property is modified in one instance of a class, the change affects all instances of the class because static properties are shared among all instances.
a) Using the $this keyword
b) Using the static keyword
c) Using the self keyword
d) Using the class name followed by :: operator
Explanation:
d) To access a static property outside of the class, weuse the class name followed by :: operator, for example: ClassName::$propertyName.
a) public
b) static
c) method
d) function
Explanation:
b) The static keyword is used to define a static method in PHP.
a) To define properties that can only be accessed within the class
b) To define properties that belong to a specific instance of a class
c) To define properties that belong to the class itself and are shared among all instances
d) To define properties that are automatically initialized with a default value
Explanation:
c) The purpose of using static properties in PHP OOP is to define properties that belong to the class itself and are shared among all instances of the class.
a) $this->propertyName
b) self::$propertyName
c) static::$propertyName
d) className::$propertyName
Explanation:
c) Within a static method, wecan access a static property using the static::$propertyName syntax.