PHP: Sub class static inheritance - children share static variables?

不打扰是莪最后的温柔 提交于 2019-11-30 21:39:22

Everything is going into only one array for two reasons:

  1. The $articles property is only defined in the Article class.

    Static class properties do not get inherited the same way you might expect if you're used to non-static properties. While they are available to the child classes, they're still referencing a single variable on the parent class - resulting in the behavior you're seeing here where both child classes are sharing the same array.

    The only way to prevent this is to define a separate array in each of your child classes, like this:

    class Report extends Article {
        public static $articles = array();
    }
    class Interview extends Article {
        public static $articles = array();
    }
    

    This actually makes sense if you think of the static variable declarations as code that gets run when the class is defined. Creating a static variable and assigning an empty array to it happens when the Article class is defined. It doesn't happen again when the Interview and Report classes are defined. There's only one time that an empty array is getting assigned - there's only one shared variable.

  2. You're using self in your add_Object_To_Array() method instead of static.

    • self:: refers to the class it is defined in, so since your add_Object_To_Array() method is defined in the Article class, it'll refer to the Article::$articles array.

    • static:: Is available starting in PHP 5.3, and refers to the class it is called on. This is known as Late Static Binding, and will result in add_Object_To_Array() referring to either Report::$articles or Interview::$articles depending on the type of the object you're calling it on.

    This code will reference the two arrays that we declared in the first step:

    public function add_Object_To_Array() {
        array_push(static::$articles, $this);
    }
    

I thought I'd present an alternate solution that changes your design slightly, but doesn't require static definitions in each subclass. Depending on your usage, this may or may not be a better option than the first solution.

This solution uses get_class() to find the type of the object we're storing, and then stores it in the parent class - in a sub-array keyed by classname:

abstract class Article
{
    public static $articles = array();

    public function add_Object_To_Array()
    {
        // get the actual class of the current object
        $class = get_class($this);
        // define an empty subarray for this class if we haven't seen it before
        if (!isset(self::$articles[$class])) {
            self::$articles[$class] = array();
        }
        // add this object to the appropriate subarray
        array_push(self::$articles[$class], $this);
    }
}
class Report extends Article{}
class Interview extends Article{}

The above code does not use late static binding, so it'll work with any PHP version, instead of just PHP 5.3+.

When you run this version with your original example, you'll get output like this:

Array
(
    [Report] => Array
        (
            [0] => Report Object
                (
                )

            [1] => Report Object
                (
                )

        )

    [Interview] => Array
        (
            [0] => Interview Object
                (
                )

            [1] => Interview Object
                (
                )

        )

)

If you do have PHP 5.3 or later, you can extend this even more and use the get_called_class() function to define a getInstances() static method (in the Article class) that works like this:

public static function getInstances()
{
    $class = get_called_class();
    // return isset(self::$articles[$class]) ? self::$articles[$class] : array();
    if (isset(self::$articles[$class])) {
        return self::$articles[$class];
    } else {
        return array();
    }
}

Then you can call this method in your example like this:

print_r(Report::getInstances());
print_r(Interview::getInstances());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!