K!

by Karl Bunyan

Programming, PHP, JavaScript, motorbikes, pubs, poker, football, news, restaurants and anything else

Friday, October 01, 2004

PHP 5 class constants and subclasses

Another one of those 'I wish PHP 5 did this...' moments has occurred to me with class constants. The addition of constants is good but the problem is when it comes to subclassing. The code on the PHP 5 site:

class Foo {
   const constant = "constant";
}

echo "Foo::constant = " . Foo::constant . "\n";

is fine. Of course, what you really want to have is a method to give you the constant in case you want to change the workings later:

class Foo {
   const constant = "constant";

   public function getConstant(){
      return self::constant;
   }
}
$foo = new Foo();
echo "$foo->constant = " . $foo::getConstant() . "\n";

and this works too. The problem is that if you decide a subclass needs a different constant value, so we add

class Bar extends Foo {
   const constant = "bar constant";
}

If we then call

$bar = new Bar();
$bar->getConstant();

then the value returned is "get_constant" i.e. the value of the constant in the parent class. This is because Bar has no handler for getConstant() so it uses its parent. That's fine, but now we're in the parent context then Foo::constant is returned through the reference to self::. The way to get round this (that I have found) is to put a copy of the getConstant() method in each of the subclasses. This kind of defeats the purpose of inheritance in this case.

class Bar extends Foo {
   const constant = "bar constant";

   public function getConstant(){
      return self::constant;
   }
}

Now we call

$bar = new Bar();
$bar->getConstant();

and the correct value is returned. Of course, the other way round is not to use constants at all but to put the value in a private variable, but then what use are constants?

Link to this post

Comments:

meep

posted by Anonymous : July 14, 2005 7:33 AM

Post a Comment

Recent posts in the Programming category

Recent posts in the PHP category

Change the background image