Nate Higgins
Nate Higgins

Reputation: 2114

Subclass overwriting parent static property

Tell me if I'm wrong, but I'm pretty sure this is a bug in PHP.

<?php

class One {

    public static $var = 'hi';
}

class Two extends One {

    public static function set($var) {
        static::$var = $var;
    }
}

Two::set('bye');

var_dump(One::$var);
// bye

That script outputs 'bye', when I'm pretty sure it should be outputting 'hi'. What do you think?

I do not want to redeclare this in the subclass.

Upvotes: 3

Views: 364

Answers (2)

Guilherme
Guilherme

Reputation: 1990

I think that is not possible, but if you don't want to redeclare simple define it in the constructor..

class One {

    public static $var = 'hi';
}

class Two extends One {

    public static $var;

    public function __construct(){
        self::$var = parent::$var;
    }

    public static function set($var) {
        self::$var = $var;
    }
}

Two::set('bye');

var_dump(One::$var);
var_dump(Two::$var);

Upvotes: 0

Marko D
Marko D

Reputation: 7576

OP edited question, this was the answer before he mentioned he doesn't want to redeclare properties

It's because Two shares $var with One.

If you would write it like this, then you would get the desired output

class One {

    public static $var = 'hi';
}

class Two extends One {

    public static $var = 'hi';

    public static function set($var) {
        static::$var = $var;
    }
}

Two::set('bye');

// you get hi
var_dump(One::$var);
// you get bye
var_dump(Two::$var);

Upvotes: 1

Related Questions