0
0
PHPprogramming~30 mins

Static properties and methods in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Static Properties and Methods in PHP
📖 Scenario: Imagine you are creating a simple system to count how many users have registered on a website. You want to keep track of the total number of users without creating a new counter for each user.
🎯 Goal: Build a PHP class with a static property to count users and a static method to display the total count.
📋 What You'll Learn
Create a class called User.
Add a static property called count initialized to 0.
Add a static method called incrementCount that increases count by 1.
Add a static method called getCount that returns the current value of count.
Call the static methods to simulate user registrations and display the total count.
💡 Why This Matters
🌍 Real World
Static properties and methods are used to keep track of information that applies to all objects of a class, like counting users, managing configuration, or caching data.
💼 Career
Understanding static members is important for backend development, especially when working with shared resources or global counters in PHP applications.
Progress0 / 4 steps
1
Create the User class with a static property
Create a class called User with a static property named count set to 0.
PHP
Need a hint?

Use public static to declare the static property inside the class.

2
Add static methods to update and get the count
Inside the User class, add a static method called incrementCount that increases count by 1, and another static method called getCount that returns the value of count.
PHP
Need a hint?

Use self::$count to access the static property inside static methods.

3
Simulate user registrations by calling the static method
Outside the User class, call the static method incrementCount three times to simulate three user registrations.
PHP
Need a hint?

Call the static method using User::incrementCount();.

4
Display the total number of users
Use print to display the text 'Total users: ' followed by the result of calling the static method getCount from the User class.
PHP
Need a hint?

Use print("Total users: " . User::getCount()); to show the count.