views:

164

answers:

3

I have the following setup:

<?php
class core {
    static $var1;
}

class parent extends core {
   function getStatic() {
       return parent::$var1;
   }
}

class child extends parent {
    function getStatic() {
        // I want to access core static var, how can i do it?
        //return parent::$var1;
   }
}
?>

I need to be able to use parent::$var1 but from within class child.. is this possible? Am I missing something?

+1  A: 

The biggest problem here is that you're using the keyword parent as a class name. This makes it completely ambiguous whether your calls to parent::$var1 are intended to point to that class, or to the parent of the calling class.

I believe, if you clean this up, you can achieve what you want. This code prints 'something', for example.

class core {
    static $var1 = 'something';
}

class foo extends core {
   function getStatic() {
       return parent::$var1;
   }
}

class bar extends foo {
    function getStatic() {
        // I want to access core static var, how can i do it?
        return parent::$var1;
   }
}

$b = new bar ();
echo $b->getStatic ();

It also works if you use core:: instead of parent::. Those two will behave differently, though, if you declare a static $var1 inside of the foo class as well. As is it's a single, inherited variable.

grossvogel
I will check this out, BTW, Its not actually called `parent` that's just a bad example.
Lizard
`parent` is a reserved keyword, PHP won't let you call your class `parent`.
NullUserException
+1  A: 

core::$var1 seems best for your needs...

ToonMariner
I'd upvote this but I don't have any votes left.
NullUserException
+2  A: 

Just reference it as self... PHP will automatically go up the chain of inheritance until it finds a match

class core {
    protected static $var1 = 'foo';
}
class foo extends core {
    public static function getStatic() {
        return self::$var1;
    }
}
class bar extends foo {
    public static function getStatic() {
        return self::$var1;
    }
}

Now, there will be an issue if you don't declare getStatic in bar. Let's take an example:

class foo1 extends core {
    protected static $var1 = 'bar';
    public static function getStatic() {
        return self::$var1;
    }
}
class bar1 extends foo1 {
    protected static $var1 = 'baz';
}

Now, you'd expect foo1::getStatic() to return bar (and it will). But what will Bar1::getStatic() return? It'll return bar as well. This is called late static binding. If you want it to return baz, you need to use static::$var1 instead of self::$var1 (PHP 5.3+ only)...

ircmaxell