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

使用变量[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.

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

报告相同问题?

悬赏问题

  • ¥15 关于#网络安全#的问题:求ensp的网络安全,不要步骤要完成版文件
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥20 使用Photon PUN2解决游戏得分同步的问题
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM