2017-05-08 81 views
1

是否可以獲得在不使用反射類的情況下在類中定義的常量?如何在不使用反射的情況下獲得php類中的常量

我想是這樣的:

<?php 

class Test { 
    const URL = 'https://www.example.com'; 

    public function get($constant) 
    { 
     return $constant; 
    } 
} 

$test = new Test(); 

$test->get('URL'); 

我所要的輸出是URL的價值,這是「https://www.example.com」。但是,現在它只是返回實際的單詞'URL'。

+0

與Test :: URL一樣簡單,如[PHP文檔](http://www.php.net/manual /en/language.oop5.constants.php) –

回答

0

另一種方式:

class Test { 
    const URL = 'https://www.example.com'; 

    public function get($constant) 
    { 
      return constant('Test::'.$constant); 
    } 
} 

$test = new Test(); 

echo $test->get('URL'); 
+0

非常感謝。這正是我正在尋找的。順便說一下,我可以將'Test ::'。$ constant'更改爲''self ::'。$ constant'嗎? – SSD

0

當然有,你只是返回輸入返回給用戶。如果您想通過名稱訪問常量,請執行以下操作:

<?php 
class Test { 
    const URL = 'https://www.example.com'; 
} 

echo Test::URL; 
+0

因爲我在MVC項目中編寫這段代碼,我想要做一些類似'$ this-> load-> model('test); $這個 - >測試 - >獲取( 'URL');'。我如何應用它? – SSD

+0

然後看看@mehulmpts的答案,他的方法可能就是你要找的。 –

相關問題