duangu8264 2018-09-19 01:00
浏览 85
已采纳

使用变量[duplicate]动态访问静态属性

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>
  • 写回答

1条回答 默认 最新

  • dongqun5769 2018-09-19 01:16
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?