Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 642
Blujacker Avatar asked Apr 14 '26 04:04

Blujacker


1 Answers

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

like image 115
djfm Avatar answered Apr 17 '26 00:04

djfm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!