Reputation: 1525
I am currently facing an inconvenience concerning accessing static members of a class served by a Registry Pattern function.
The ideal code I would like to use is below. It accesses a constant in the base class, that is served via the static method get()
of the registry class.
echo "<link rel='shortcut icon' href='" . Registry::get('base')::SHORTCUT_ICON . "'>";
At the moment I can only work the code like this:
$base = Registry::get('base');
echo "<link rel='shortcut icon' href='" . $base::SHORTCUT_ICON . "'>";
I don't know exactly what this feature would be called, however I thought something similar was being introduced in PHP 5.4 - Access array returned by a function in php. And here https://wiki.php.net/rfc/functionarraydereferencing
Question
Is there a neat one-line solution around this problem, or will it have to remain a messy two-liner?
Upvotes: 0
Views: 81
Reputation: 17361
A very simple way to get around the problem is to create a convenience wrapper for retrieving the static members. A wrapper approach works best if you can provide an instance to wrap around. Since you have a class with static members you will need to have a hardcoded dependency on Registry
. Unless you can provide an instance off course.
The ideal situation
class RegistryBaseWrapper {
private $registry;
public function __construct(Registry $registry) {
$this->registry = $registry;
}
public function getShortcutIcon() {
$base = $this->registry::get('base');
return $base::SHORTCUT_ICON;
}
}
$wrapper = new RegistryBaseWrapper($registry);
echo $wrapper->getShortcutIcon();
Less ideal but it will work as well
class RegistryBaseWrapper {
public function getShortcutIcon() {
$base = Registry->get('base');
return $base::SHORTCUT_ICON;
}
}
$wrapper = new RegistryBaseWrapper();
echo $wrapper->getShortcutIcon();
P.s. Don't focus too much on creating oneliners with static variables and direct class references. They will create dependencies which will be hard to manage in the future. If you're writing this code for a quick throw-away project then it's OK. If this is a project that needs future work don't.
Upvotes: 1
Reputation: 3831
The only thing I can come up with is this:
constant(get_class(Registry::get('base')).':: SHORTCUT_ICON');
Not sure this is a better solution though, since readability suffers immensely.
Something else you might want to do is to create a getClassName()
function in your Registry
class, which would just return the name of the class. Then you can do
constant(Registry::getClassName('base').':: SHORTCUT_ICON')
which is a little more clear.
Upvotes: 0