0

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( $dataSource)
    {
        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?

  • possible duplicate of [PHP5 & Abstract Classes. Separate copy of class variables for each child class?](http://stackoverflow.com/questions/3391788/php5-abstract-classes-separate-copy-of-class-variables-for-each-child-class) – Artefacto Aug 09 '10 at 17:58
  • see also http://stackoverflow.com/questions/3187124/peculiar-behaviour-with-php-5-3-static-inheritance-and-references – Artefacto Aug 09 '10 at 18:00

2 Answers2

2

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

Community
  • 1
  • 1
Artefacto
  • 96,375
  • 17
  • 202
  • 225
0

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...

ircmaxell
  • 163,128
  • 34
  • 264
  • 314