2

I want to get the value of the static var that was redeclared in the subclass :

    class A {

        private static $echo_var = 'PARENT_ECHO' ;

        public static function e() {
            return '$echo_var = ' . self::$echo_var ;
        }
    }

    class B extends A {

        private static $echo_var = 'CHILD_ECHO';
    }

    echo B::e();

I want to get CHILD_ECHO.

thanks, Mottenmann

Mottenmann
  • 413
  • 1
  • 4
  • 12

2 Answers2

6

Use the static keyword when accesing it:

return '$echo_var = ' . static::$echo_var ;

It's called late static binding. But it won't work on private members. You'll have to make it public or protected. Private properties are accessible only in the class in which they are defined.

nice ass
  • 16,471
  • 7
  • 50
  • 89
  • wonderfull ! Thank you very much i knew about late static binding but never really understood how to use the static:: . But its so simple :) – Mottenmann May 14 '13 at 09:42
3

There are 3 errors:

  • ECHO is a reserved name.
  • Use protected instead of private
  • Use static instead of self
class A
{

    protected static $echo_var = 'PARENT_ECHO' ;

    public static function output()
    {
        return '$echo_var = ' . static::$echo_var ;
    }
}

class B extends A
{
    protected static $echo_var = 'CHILD_ECHO';
}

echo B::output();
shadyyx
  • 15,825
  • 6
  • 60
  • 95
bitWorking
  • 12,485
  • 1
  • 32
  • 38