class Calc { const PROP = TRUE; } class PHP_Unit_Test { static protected $testModel; public static function setUpBeforeClass() { self::$testModel = new Calc(); } public function test_some_method() { // вот тут как мне получить значение константы класса Calc? // приведенная ниже строка конечно неправильная, она для демонстрации self::$testModel::PROP; } } 

    2 answers 2

    In fact, your task is to obtain a class constant from an instance of this class. The easiest way is to use the get_class function:

     class Calc { const PROP = true; } $c = new Calc(); $class_name = get_class($c); var_dump($class_name::PROP); // bool(true) 

    A working example on IDEOne .

    For your particular case:

     // ... public function test_some_method() { $class_name = get_class(self::$testModel); var_dump($class_name::PROP); } // ... 

      You can do the following. Generate the string "Calc :: PROP" and pass it to the function constant() , which returns the value of the class constant

       <?php class Calc { const PROP = TRUE; } class PHP_Unit_Test { static protected $testModel; public static function setUpBeforeClass() { self::$testModel = new Calc(); } public function test_some_method() { // вот тут как мне получить значение константы класса Calc? // приведенная ниже строка конечно неправильная, она для демонстрации //self::$testModel::PROP; return constant(get_class(self::$testModel)."::PROP"); } } $obj = new PHP_Unit_Test(); $obj->setUpBeforeClass(); echo $obj->test_some_method(); 
      • In fact, the constant function is not needed at all. - Dmitriy Simushev
      • @DmitriySimushev, without it, do not get the value of a constant - cheops
      • It only seems that way to you. Proof: ideone.com/mqJ4zQ - Dmitriy Simushev
      • Yes, I agree, if you arrange the name of the class as a separate variable. - cheops