Skip to Content
Course content

22: Static Properties and Methods

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're running a company. Every single employee you hire has their own name, their own desk, and their own salary. Those are individual traits. If you want to know the name of an employee, you have to go to that specific person and ask them. In PHP terms, those are your standard instance properties.

But then, consider the company's headquarters address. Does every employee need to carry a separate copy of the office address in their pocket? No. The address belongs to the company itself. It doesn't matter which employee you ask; the answer is the same because the address is a property of the organization, not the individual. That's exactly how static properties and methods work.

Sharing Data Across All Instances

Usually, when you create a class, you use the new keyword to create an object. Each object gets its own set of data. But sometimes, you need a variable that is shared across every single instance of that class. We use the static keyword for this.

Take a look at this User class. I want to keep track of how many users have been created during the current script execution. If I used a regular property, every user would just have their own count starting at 1. By making it static, they all share one single counter.

class User {
    public static $userCount = 0;
    public $username;

    public function __construct($username) {
        $this->username = $username;
        // We use 'self::' instead of '$this->' for static properties
        self::$userCount++;
    }
}

$user1 = new User("Alice");
$user2 = new User("Bob");

echo User::$userCount; // Outputs: 2

Notice two things here. First, I accessed the property using User::$userCount without ever needing an object. Second, inside the constructor, I used self::$userCount. I've seen a lot of developers try to use $this->userCount here and wonder why it fails. Remember: $this refers to the specific object instance, but self refers to the class itself.

Utility Methods That Don't Need an Object

Similarly, we have static methods. These are functions that live inside a class because they are logically related to it, but they don't actually need any data from a specific object to do their job. I call these "utility" or "helper" methods.

Think of a Password class. You might want a method that checks if a string meets your complexity requirements. You don't need to create a "Password Object" just to check if a string has eight characters; you just need the logic.

class PasswordHelper {
    public static function validate($password) {
        if (strlen($password) < 8) {
            return false;
        }
        return true;
    }
}

// No 'new PasswordHelper()' needed!
if (PasswordHelper::validate("12345")) {
    echo "Strong password!";
} else {
    echo "Too short!";
}

By making validate() static, we've made the code cleaner. We aren't wasting memory creating objects that don't hold any state; we're just using the class as a container for a useful tool.

The Great "Static vs Instance" Divide

Here is the one rule that will save you hours of debugging: A static method cannot use $this.

Why? Because $this represents the current object instance. If you call a method using ClassName::method(), no object was ever created. There is no $this. If you try to access $this->someProperty inside a static method, PHP will throw a fatal error.

I generally recommend using static methods sparingly. It's tempting to make everything static because it feels "easier" to call, but it can make your code harder to test later on. Use them for tools (like the password validator) or shared counters, but keep your core business logic tied to objects.




📋 Practical Task

Build a Global Site-Settings Manager

You need to create a class called SiteConfig that manages global configuration settings for a website. Since these settings (like the site name and the maintenance mode status) should be the same across the entire application, they should be static.

Requirements:

  • Create a class SiteConfig.
  • Add a public static property $siteName and initialize it to "My Awesome Portal".
  • Add a public static property $isMaintenanceMode and initialize it to false.
  • Create a static method called toggleMaintenance() that switches the value of $isMaintenanceMode (if it's true, make it false, and vice versa).
  • Create a static method called getWelcomeMessage() that returns a string: "Welcome to [siteName]!".

Test your code by:

  1. Printing the welcome message using the static method.
  2. Calling toggleMaintenance() and printing the new value of $isMaintenanceMode to verify it changed.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.