在PHP中使用存储在const中的属性名称

时间:2016-12-22 09:45:17

标签: php const

我想访问名称存储在const。

中的属性
class Foo
{
     const PROPERTY_NAME = 'bar';

     protected $bar;

     public function getBar() {
         return $this->self::PROPERTY_NAME;
     }

}

关于如何做到这一点的任何想法?

2 个答案:

答案 0 :(得分:3)

使用Variable variables

 public function getBar() {
     return $this->{self::PROPERTY_NAME};
 }

<强> Fiddle

答案 1 :(得分:0)

试试这个:

class MyClass
{
    const MYCONSTANT = 'constant value';

    function showConstant() {
        echo  self::MYCONSTANT. "\n";
    }
}

$classname = "MyClass";
echo $classname::MYCONSTANT. "\n"; // As of PHP 5.3.0

//输出:常量值