Static Properties

Last updated on

Static properties let you store data across different objects which helps us to keep the shared information in one place. This keeps your code more cleaner.

In the next sections, you will see why and how to use PHP static properties, let's get started.

What are Static Properties in PHP

Static properties belong to the class, not to individual instances. When a property is declared as static, every instance of the class can access and modify the same piece of data.

So instead of creating a new version of that data for every object, PHP lets all objects in a class "share" one variable. This is great for values you want to keep the same across all instances, like a counter or a default setting.

Here is an example:

class Counter {
    public static $count = 0;

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

So every time a new Counter object is created, the shared $count property increments, regardless of how many instances there are.

Let's take a look at the following section, to understand how to access Static Properties in PHP.

Accessing PHP Static Properties (No Instances Required!)

You do not need to create an instance of the class to access when you use static properties. Instead, you can reach them directly through the class name using the :: syntax, also called the scope resolution operator.

Here is an example:

class Greeting {
    public static $message = "Hello, PHP!";

    public static function displayMessage() {
        return self::$message;
    }
}

// Accessing the static property
echo Greeting::$message; // Outputs: Hello, PHP!

In this case, you can get Greeting::$message directly, without creating an instance of Greeting. It is like having a single bulletin board that everyone can see and update, rather than giving everyone their board.

In the following section, you will learn how to apply this concept through examples.

Examples of PHP Static Properties

Consider users logging in and out of your website. So you need to track the number of active users is a good use for static properties because it allows all instances of a class to update a single shared counter.

class User {
    public static $activeUsers = 0;

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

    public function __destruct() {
        self::$activeUsers--;
    }
}

// Create new users
$user1 = new User();
echo User::$activeUsers; // Outputs: 1

$user2 = new User();
echo User::$activeUsers; // Outputs: 2

So, with each new User, the shared activeUsers count goes up. When a user is removed (or the object is destroyed), the count decreases. This method keeps everything in sync without cluttering each instance with individual counters.

Another common usage of static properties is in setting defaults that all instances rely on. For instance, if you are building a pricing system, you might want a default tax rate that applies to every item. A static property keeps this setting accessible across all instances of the class.

class Pricing {
    public static $defaultTaxRate = 0.07; // 7%

    public static function calculateWithTax($amount) {
        return $amount * (1 + self::$defaultTaxRate);
    }
}

// Access default tax rate
echo Pricing::calculateWithTax(100); // Outputs: 107

The tax rate is consistent across every calculation. If you ever need to adjust the rate, changing it once updates it for all calculations using the Pricing class.

let's summarize it.

Wrapping Up

PHP static properties allow you to create a single and shared property for all instances of a class. This can be useful when you want a variable to remain consistent across every object created from that class. With static properties, you avoid repetition, and save memory to shared data.

  • Static Property: A variable that belongs to a class, not individual instances.
  • Scope Resolution Operator (::): The syntax used to access static properties directly through the class name.
  • Optimized Memory Usage: By using static properties, you can prevent unnecessary duplication across instances.

That's it, if you need to read more tutorials in PHP, click here. Thank you for reading.

Frequently Asked Questions (FAQs)

  • What are 'static properties' in PHP?

    Static properties are variables that belong to a class rather than its instances. This allows every instance of a class to access the same data, which is useful for shared values like counters or default settings.
  • How do I declare a static property in PHP?

    You declare a static property with the static keyword within a class. Example:
    class Example {
        public static $sharedData = "This is shared!";
    }
  • How can I access a static property in PHP?

    Static properties are accessed directly through the class name using the scope resolution operator ::, without needing an instance. Example:
    echo Example::$sharedData;
  • When should I use static properties?

    Use static properties when you need shared data across all instances of a class, like counters, configuration values, or defaults that remain the same across objects.
  • How do static properties save memory in PHP?

    Static properties are stored once per class, rather than duplicating the variable across instances. This reduces memory use, especially with many objects.
  • How can I increment a counter with static properties in PHP?

    A static property can track increments across instances. Example:
    class Counter {
        public static $count = 0;
    
        public function __construct() {
            self::$count++;
        }
    }
  • Can I access static properties inside a class method?

    Yes, access them with self:: and the property name. Example:
    class Example {
        public static $sharedData = "Hello!";
    
        public static function getData() {
            return self::$sharedData;
        }
    }
  • How do static properties help with setting default values?

    Static properties can store default settings shared across instances, like a tax rate:
    class Pricing {
        public static $defaultTaxRate = 0.07;
    
        public static function calculateWithTax($amount) {
            return $amount * (1 + self::$defaultTaxRate);
        }
    }
    echo Pricing::calculateWithTax(100); // Outputs: 107
  • What is the scope resolution operator in PHP?

    The scope resolution operator :: allows access to static properties and methods directly through the class name.
  • What is an example of tracking users with static properties?

    You can track active users by incrementing a shared counter:
    class User {
        public static $activeUsers = 0;
    
        public function __construct() {
            self::$activeUsers++;
        }
    
        public function __destruct() {
            self::$activeUsers--;
        }
    }
    $user1 = new User();
    echo User::$activeUsers; // Outputs: 1
    $user2 = new User();
    echo User::$activeUsers; // Outputs: 2
Share on: