【问题标题】:Access constant members of one class inside another class member在另一个类成员中访问一个类的常量成员
【发布时间】:2013-05-11 04:08:57
【问题描述】:

我有以下课程:

class Mode{
    const Enabled = 1;
    const Disabled = 2;
    const Pending = 3;
}
class Product{
    public static $Modes = Mode;
}

我想通过 Product 的静态访问来访问 Mode 类的常量。

if($product_mode == Product::$Modes::Pending){
    //do something
}

有什么办法吗?

【问题讨论】:

  • 你能扩展你的用例吗?在我看来,您好像在做错事。
  • 我正在使用 autoload 来自动加载我的类,所以如果我将 Mode 类放在 Product.php 中,它只会在使用 Product 时自动加载。当我直接调用 Mode::Pending 而不使用 Product 时,会发生错误,告知 Mode 类不存在。
  • ModeProduct 是否声明在一个文件中?

标签: php class static constants


【解决方案1】:

你可以这样做:-

if($product_mode == Mode::Pending){
    //do something
}

在 Product 类中,尽管我怀疑它是实现您想要做的任何事情的最佳方式。

【讨论】:

    【解决方案2】:

    我找到了办法:

    class Base{
        static public function getC($const)
        {
            $const = explode('/', $const);
            if(count($const)!=2)
                return;
            $cls = new ReflectionClass($const[0]);
            $consts = $cls->getConstants();
            return $consts[$const[1]];
        }
    }
    class Mode{
        const Enabled = 1;
        const Disabled = 2;
        const Pending = 3;
    
    }
    class Product extends Base{
    
    }
    
    echo Product::getC('Mode/Pending');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多