Some PHP5 Gotchas

Fiddling around with PHP5, I’ve stumbled upon some interesting gotchas, some of them might be too obvious to mention, but sometimes the obvious is only too obvious that we don’t even notice.

Static variables and functions

PHP5 supports both static variables and functions (i.e. do not need an instance to be called), but for some reason, PHP5 doesn’t allow overriding static variables in a subclass:


<?php
class Base
{
    static $var = 4;
}

class Sub extends Base
{
    static $var = 5;
}
?>

Fatal error: Cannot redeclare property static public Base::$var in class Sub in /path/to/script.php on line 13

Interestingly enough, static functions can can be overridden, so the following code would run without any errors:


<?php
class Base
{
    static function func()
    {
         echo “Called from Base\n” ;
    }
}

class Sub extends Base
{
    static function func()
    {
         echo “Called from Sub\n” ;
    }
}

Base::func(); // outputs “Called from Base”
Sub::func(); // outputs “Called from Sub”
?>

Variable class names

Methods cannot be called statically if the class name is stored in a variable, I’m not very sure why, but I’d guess it was too much of a headache to implement. For example:


<?php
class Base
{
    static function func()
    {
         echo “Called from Base\n” ;
    }
}

$class = ‘Base’;
$class::func(); // WRONG!
?>

Would generate:

Parse error: parse error, unexpected T_PAAMAYIM_NEKUDOTAYIM in /path/to/script.php on line 52

The only way to do it is to use call_user_func() or call_user_func_array(). Using the above Base class, this is how func() should be called:


<?php
    call_user_func(array($class, ‘func’));
?>

Same applies to calling class constants, there’s no way to get a class constant with a variable class name without using constant().


<?php
class Base
{
    const BASE_CONST = ‘CONST_VALUE’;
}

$class = ‘Base’ ;
echo $class::BASE_CONST; // WRONG!
echo constant(”$class::BASE_CONST”); // RIGHT
?>

 

I know that these are some picky stuff, but I still would like PHP to support these, because at the very least, the code would look better.

Comment (1)

  1. Claude Hartman wrote:

    6rg4apgti1mdi80q

    Thursday, November 13, 2008 at 4:48am #