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?

Advertisements
This entry was posted in PHP, Programming. Bookmark the permalink.

One Response to PHP 5 class constants and subclasses

  1. Anonymous says:

    meep

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s