Question

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

Was it helpful?

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 :)

OTHER TIPS

Although you should avoid such constructions, you could solve it quite nicely:

<?php

class Fruit {
    protected static $names;
    public static function setName($name)
    {
        self::$names[get_called_class()] = $name;
    }

    public static function getName()
    {
        return isset(self::$names[$key = get_called_class()]) ? self::$names[$key] : null;
    }
}

So basically you store the data in just a single class, but specific to the class the method was called on. You don't need static as $name is always part of self, but 5.3 is still required because get_called_class is also part of late static binding.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top