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.

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

报告相同问题?

悬赏问题

  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划