PHP Static Property: How It Works & Examples

php-static-property

PHP static property helps you manage shared data across instances, but can lead to hidden state changes. In this article, we will cover the following topics:

  • What is a static property in PHP?
  • How it works, and how to access a static property from the class.
  • Examples.

Let’s start with its definition.

Understand What a Static Property Is in PHP

A static property belongs to a class rather than any specific instance. It uses the static keyword and access it with.

Here is a quick example:

class Motorcycle {
    public static $numberOfWheels = 4;
}

// Access the static property
echo Motorcycle::$numberOfWheels; // 4

You don’t need to create an object to access $numberOfWheels. It belongs to the Motorcycle class itself.

So, how does it differ from regular properties?

Here is a table showing you the differences between them:

Key differencesStatic propertyRegular property
Access PropertyClassName::$property$object->property
Instance DependencyExists at the class level, shared across all instancesEach object gets its own copy.
Memory UsageStored once in memory for the class.
Each instance holds its own value in memory.

Here is an example that shows you two together:

class Machinery {
    // This is a static property. It belongs to the class, not instances.
    public static $staticProperty = "I belong to the class";
    
    // This is a regular property. Each instance gets its own copy.
    public $regularProperty = "I belong to an instance";
}

You can access static properties directly when you use the class name without creating an object:

// output: "I belong to the class"
echo Machinery::$staticProperty; 

Here are its instances:

// Create two instances of the Machinery class
$machine1 = new Machinery();
$machine2 = new Machinery();

We created two separate objects ($machine1 and $machine2). Each object has its own copy of the regular property.

Each instance has its own separate copy of the regular property. It is in one object and does not affect the other.

// Access the regular property from both instances
echo $machine1->regularProperty; // Output: "I belong to an instance"
echo $machine2->regularProperty; // Output: "I belong to an instance"

Here is the full example:

class Machinery{
    public static $staticProperty = "I belong to the class";
    public $regularProperty = "I belong to an instance";
}

echo Machinery::$staticProperty; 

$machine1 = new Machinery();
$machine2 = new Machinery();

echo $machine1->regularProperty; // Unique to this instance
echo $machine2->regularProperty; // Separate copy

Let’s see the most common issue when using the static property of the class.

Fix Issues Related to Static Property in PHP

Here is another issue when you declare a static property that does not exist inside the class.

Error 1: Property not defined.

class Bicycle{
    public static function show() {
        echo self::$name; // Error: $name property is not defined
    }
}

Bicycle::show();

This will show you the following error:

PHP Fatal error:  Uncaught Error: Access to undeclared static property Bicycle::$name in /bicycle.php:5

Here is the correct code:

class Bicycle{
    
    // => Define the $name
    private static $name = "Leno Cobra"; 
    
    public static function show() {
        echo self::$name; 
    }
    
}

Bicycle::show();

You cannot access a regular class property using self::$property.

Error 2: Access a non-static property as static (Access undeclared static property).

class Verb {
    public $singular = "Is";

    public static function toBe() {
        echo self::$singular; // => Error: $name is not static
    }
}

Verb::toBe();

This will show you the following error:

PHP Fatal error:  Uncaught Error: Access to undeclared static property Verb::$singular in /verb.php:7

Here is the correct code:

class Verb {
    private static $singular = "Is";

    public static function toBe() {
        echo self::$singular; // => Error: $name is not static
    }
}

Verb::toBe();

Let’s move on to the following part to see more examples.

PHP Static Property Examples

Example 1: This class maintains a list of supported credit card types.

class CreditCards {

    private static $supportedCards = ['Visa', 'MasterCard', 'American Express'];

    public static function getSupportedCards() {
        // => The static is private here so we used self
        return self::$supportedCards;
    }
    
}

// => Used a public method to showcase a private static property.
print_r(CreditCards::getSupportedCards());

Output:

Array
(
    [0] => Visa
    [1] => MasterCard
    [2] => American Express
)

Example 2: This class provides a method to validate bank routing numbers:

class Banks {
    public static function validateRoutingNumber($routingNumber) {
        // Example validation: routing number must be 9 digits
        return preg_match('/^\d{9}$/', $routingNumber);
    }
}

// Use this static method to validate a routing number
$isValid = Banks::validateRoutingNumber('123456789');
echo $isValid ? 'Valid' : 'Invalid'; 

Here is the output:

Valid

Example 3: This class provides utility methods for financial calculations.

class Accountings {
    public static function calculateVAT($amount, $vatRate) {
        return $amount * $vatRate / 100;
    }
}

// Using the static method to calculate VAT
$vat = Accountings::calculateVAT(1000, 15);
echo $vat;

Output:

150

Wrapping Up

In this tutorial, you learned what a static property is in PHP and how it works.

Here’s a quick recap:

  • Static properties belong to the class, not instances.
  • They use the static keyword and are accessed with ClassName::$propertyName.
  • Static properties are shared across all instances if you don’t need to use regular properties.
  • Use them for shared data like counters, configuration values, and utility functions.

FAQ’s

What is a static property in PHP?

A static property in PHP belongs to a class rather than an instance. It is defined using the static keyword and accessed using ClassName::$property.

How do I declare a static property in PHP?

You declare a static property inside a class using the static keyword. Here is example:
class Persons {
    public static $name = "Hajar";
}

How do I access a static property in PHP?

You access a static property using the class name and :: (scope resolution operator):

echo Persons::$name;

Can I access a static property using an object?

Yes, but it’s not recommended. You should access it using the class name:

$obj = new Persons();
echo $obj::$name;

Can static properties be private or protected?

Yes, you can use private or protected for static properties. Use a getter method to access them.

What error occurs if I access an undefined static property?

If you try to access an undeclared static property, you get:
Error: Fatal error: Uncaught Error: Access to undeclared static property

Can I modify a static property?

Yes, you can change its value like this:

Persons::$name = "Nader";
echo Persons::$name;

Can static properties be inherited in PHP?

Yes, child classes inherit static properties from parent classes:

class ParentClass {
    protected static $value = "Hello FlatCoding!";
}

class ChildClass extends ParentClass {
    public static function getValue() {
        return self::$value;
    }
}

echo ChildClass::getValue();
Previous Article

Inheritance in PHP: Share Code from Class to Class & Examples

Next Article

PHP Null: How to Assign and Check for Null Values

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.