This question already has an answer here:
I'm trying to dynamically access a static namespaced property (using delight-im's auth
). Possible values could be:
\Delight\Auth\Role::ADMIN
\Delight\Auth\Role::USER
etc
I want to name the ADMIN
part dynamically, as such:
\Delight\Auth\Role::$role
But PHP is telling me:
Access to undeclared static property: Delight\Auth\Role::$role
So I tried to use a variable variable as such:
\Delight\Auth\Role::$$val
(two $
s) and the error changes to:
Access to undeclared static property: Delight\Auth\Role::$ADMIN
So as you can see the variable is resolved, but there is a $
inserted in there still. I'm using PHP 5.6.37
if that makes a difference.
Is there a way to access static properties dynamically like this?
</div>
You're mixing up your terminology. The syntax you're using is accessing a class's static property, but you're describing features of a class constant.
Static properties are mutatable variables stored on the class. Example from the PHP manual:
<?php
class Foo
{
public static $my_static = 'foo';
public function staticValue() {
return self::$my_static;
}
}
You'd reference $my_static like this: Foo::$my_static
, which is what you're doing.
Class constants seems to be what you're describing. Example from the PHP manual:
<?php
class MyClass
{
const CONSTANT = 'constant value';
function showConstant() {
echo self::CONSTANT . "
";
}
}
You'd reference CONSTANT like this: MyClass::CONSTANT
.
Here's a better answer describing how to reference class constants dynamically, which is what you're attempting to do.