Search code examples
phpfunctionclassstatic

Any alternative to static functions that does not share data with objects? [PHP 8.3]


Lets say I have this class with an static function:

<?php

class Myclass {

    public static $example = 0;

    public static function Example() {
        echo self::$example;
    }

    public function __construct($value) {
        self::$example = $value;
    }
}

Myclass::Example(); // This will print 0

$dummy = new Myclass(1);

Myclass::Example(); // This will print 1

?>

So it seems that the Example() function is influenced by the new instance created, and is not something separated from the object. My skill issue mind cannot comprehend this yet.

In my mind, the print 1 should only happen when I did $dummy::Example(), but not only this is a bad pratice, the result is the same as Myclass::Example() after the object is created.

Should I just create an public function if I want their value to be inside some "container", or there is any alternative?


Solution

  • Myclass::Example();
    

    prints 0 because in PHP, static properties of a class gets shared accross all instances of a class. Any change in one instance changes it for every instances.

    If I add another instance after the first declaration as such

    $dummyTwo = new MyClass(2);
    
    Myclass::Example();
    

    will print 2.

    You should avoid using static properties and methods in your case, because you won't even be able to use $this inside a static method. https://www.php.net/manual/en/language.oop5.static.php