Reputation: 2114
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
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
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