Class name constants in PHP 5.4

Submitted by Larry on 12 January 2015 - 6:23pm

One of the nice new features of PHP 5.5 is automatic class name constants. That is, in PHP 5.5 you can do this:

<?php
namespace Something\Obscenely\Long\Hard\To\Type;

class MyClass {
}

echo MyClass::class;
// Output: Something\Obscenely\Long\Hard\To\Type\MyClass
?>

That's super useful anywhere you want to specify a class name as a string, rather than a data type. ORM objects are one place that crops up often, as is testing. There are a lot of use cases for wanting to enter a class name as a string, and before PHP 5.5 it was really annoying to do.

However, a nice gentleman named Yannick Voyer pointed out to me on Twitter the other day that there is a workaround for earlier versions thanks to pre-existing magic constants!

<?php
namespace Something\Obscenely\Long\Hard\To\Type;

class MyClass {
  const CLASSNAME = __CLASS__;
}

echo MyClass::CLASSNAME;
// Output: Something\Obscenely\Long\Hard\To\Type\MyClass
?>

Score! There's barely any memory impact, since as a constant it gets resolved at compile time. It's just a bit uglier than the native version.

I wouldn't do this everywhere, but for testing classes it's really useful and really easy.

Technically this trick works on PHP 5.3 and later, but if you're still on PHP 5.3 please do yourself a favor and just upgrade. You're running known-insecure software.