Re: Protected static props redeclared as public share value across classes

From: Date: Mon, 28 Jan 2008 17:37:25 +0000
Subject: Re: Protected static props redeclared as public share value across classes
References: 1 2 3 4  Groups: php.internals 
Request: Send a blank email to internals+get-34968@lists.php.net to get a copy of this message
Marcus, Thanks for looking in more detail. > I checked it out in more detail and it is indeed broken as in it is not > consistent: > [marcus@zaphod PHP_5_3]$ php -r 'class A { protected static $p=1; } class B extends A { > protected static $p=2; } ReflectionClass::Export("B");' > -> works == 2 properties > -> but should fail because of changed value > > [marcus@zaphod PHP_5_3]$ php -r 'class A { protected static $p=1; } class B extends A { > public static $p=2; } ReflectionClass::Export("B");' > Fatal error: Cannot change initial value of property static protected A::$p in class B in > Command line code on line 1 > > [marcus@zaphod PHP_5_3]$ php -r 'class A { public static $p=1; } class B extends A { > protected static $p=2; } ReflectionClass::Export("B");' > Fatal error: Access level to B::$p must be public (as in class A) in Command line code on line > 1 > > [marcus@zaphod PHP_5_3]$ php -r 'class A { public static $p=1; } class B extends A { > public static $p=2; } ReflectionClass::Export("B");' > -> works == 2 properties > -> but should fail becasue of changed value > > So we need to fix this. > I agree with Jochem: I'm not fully confident about the statement 'but should fail because of changed value', for two reasons: 1. The issues doesn't stop with default values. Consider the case below. If we were go with your suggested fix, the parent and child class "feel" like they have separate properties, but in fact point to the same value. It is imho more natural for the two classes to genuinely have separate values. Another alternative would be to forbid redeclaring statics with the same visibility modifier altogther (default value or no default value), though I would personally be less happy with that. <?php Class Frog { public static $colour; } Class SpecialFrog extends Frog { public static $colour; } Frog::$colour = 'green'; SpecialFrog::$colour = 'blue'; var_dump(Frog::$colour, SpecialFrog::$colour); // string(4) "blue" // string(4) "blue" ?> 2. The suggested fix would create an inconsistency with class constants, where it is legal to shadow inherited values: <?php Class Frog { const COLOUR = 'green'; } Class SpecialFrog extends Frog { const COLOUR = 'blue'; } var_dump(Frog::COLOUR, SpecialFrog::COLOUR); // string(5) "green" // string(4) "blue" ?> Many thanks, Robin

« previous php.internals (#34968) next »