开发者

late static in PHP 5.3 doesn't produce expected result while inherit

开发者 https://www.devze.com 2023-01-10 16:34 出处:网络
I have a problem with static keyword due to inheritance in PHP 5.3. abstract class Object { protected static $_classDataSource = null;

I have a problem with static keyword due to inheritance in PHP 5.3.

abstract class Object
{
    protected static $_classDataSource = null;

    public static function getDataSource()
    {
        return static::$_classDataSource;
    }

    public static function setDataSource( $dataSourc开发者_JAVA技巧e)
    {
        static::$_classDataSource = $dataSource;
    }
}

class Film extends Object
{

}

class Actor extends Object
{

}
Film::setDataSource('FFF');
Actor::setDataSource('aaa');
echo Film::getDataSource();
echo Actor::getDataSource();

Result is: aaaaaa Expected result: FFFaaa

What should I do to make it as expected?


You need to redeclare the static variables in the child classes or break the reference set manually. See this answer.


I know it's not technically answering your exact question, but I have to ask: Why? If you need configuration (such as setting a data source), in most cases it's better to use instances...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号