2

I have the following stucture

class Foo
{
    public static $a = "parent";

    public static function Load()
    {
        return static::$a;
    }

    public function Update()
    {
        return self::$a; 
    }

}

class Bar extends Foo
{
    private static $a = "child";
}

I want the Update function to be able to return $a aswell, but I can't get it to work.

Bar::Load();  //returns child, Correct.
$bar = new Bar();
$bar->Update(); //returns parent, Wrong.

I've tried self:: , static:: and get_class() without success.

Artmann
  • 130
  • 3
  • 14

2 Answers2

3

Change self::$a in update()

class Foo
{
    protected static $a = "parent"; // Notice this is now "protected"

    public function child()
    {
        return static::$a; 
    }

    public function parent()
    {
        return self::$a; 
    }
}

class Bar extends Foo
{
    protected static $a = "child"; // Notice this is now "protected"
}

$bar = new Bar();
print $bar->child() . "\n";
print $bar->parent() . "\n";
Xeoncross
  • 55,620
  • 80
  • 262
  • 364
  • 2
    Isn't the real error that `$a` is being declared as private when it's public in the parent class? – tigrang Jul 18 '12 at 16:36
  • @tigrang, I wondered about that also, but if they aren't getting any errors then it would only be a recommended/strict change and shouldn't effect the actual execution. – Xeoncross Jul 18 '12 at 16:37
  • I'm trying with php 5.4 and 5.3.10 and getting a fatal error because of it. http://codepad.viper-7.com/2THHHk – tigrang Jul 18 '12 at 16:38
1

See my code

class Foo
{
    protected static $a = "parent";

    public static function Load()
    {
        return static::$a;
    }

    public function Update()
    {
        return static::$a; 
    }

}

class Bar extends Foo
{
    protected static $a = "child";
}
Bar::Load();  //returns child, Correct.
$bar = new Bar();
$bar->Update(); //returns child, Correct.
Navneet Garg
  • 1,364
  • 12
  • 29