Search code examples
phpclassstaticextendlate-static-binding

Create two same static classes in PHP


I am trying to extend static class in PHP. What I am running into is that once I change the variable in one of the extend classes, all others classes are changes as well. This is what I am trying to do:

class Fruit{
    private static $name = Null;
    public static function setName($name){
        self::$name = $name;
        }
    public static function getName(){
        return self::$name;
        }
    } 

class Apple extends Fruit{};
class Banana extends Fruit{};

Apple::setName("apple");
Banana::setName("Banana");

echo Apple::getName();
echo Banana::getName();

I have read about late static binding and the keyword static::. But I cannot think of a way how to accomplish this without having to redeclare all Fruit's methods in both Apple and Banana.

I will be happy for any help

Thank You


Solution

  • This works:

    <?php
    
    class Fruit{
        protected static $name = Null;
        public static function setName($name){
            static::$name = $name;
            }
        public static function getName(){
            return static::$name;
            }
        } 
    
    class Apple extends Fruit{protected static $name;};
    class Banana extends Fruit{protected static $name;};
    
    Apple::setName("apple");
    Banana::setName("Banana");
    
    echo Apple::getName();
    echo Banana::getName();
    

    Unfortunately you need to re-declare the static properties you want to specialize, but your late static binding intuition was right :)