2014-01-10 51 views
-5

我开始学习php,最近我在代码中遇到了一个常量变量的问题。最近我在编辑器中创建了Ninja类,并为字符串“MAXIMUM”设置了一个隐形常量,然后使用范围解析运算符(::)尝试将其回显到页面。如何在PHP中使用变量名称回显常量变量

<html> 
<head> 
<title> Scope it Out! </title> 
</head> 

<body> 

<p> 
    <?php 
    class Person { 

    } 
    class Ninja extends Person { 
    // Add your code here... 
    const stealth = "Maximum"; 
    } 
    // ...and here! 
    if(Ninja::stealth){ 

    echo stealth; 
    } 

    ?> 

    </p> 

</body> 

</html> 

现在的问题是 “如何呼应在PHP 常数变量 ???”

+2

'回声忍者::隐形'。仅供参考,常用大写字母命名常量。 –

+1

您在'if'测试中访问它的方式相同:'echo Ninja :: stealth' –

+1

@BrokenHeartღ - 并非真正的重复:'stealth'是一个常量,不是变量 –

回答

3

你已经访问它通过echo Ninja::stealth;
试试这个:
现场演示:https://eval.in/88040

class Person { 

     } 
     class Ninja extends Person { 
     // Add your code here... 
     const stealth = "Maximum"; 
     } 
     // ...and here! 
     if(Ninja::stealth){ 
     echo Ninja::stealth; 
     } 

输出:

Maximum 
1

或者是这样的:

<?php 
    class Person { 

    } 
    class Ninja extends Person { 
    // Add your code here... 
    const stealth = "Maximum"; 
    public function getCamo() 
    { 
     return self::stealth; 
    } 
    } 

    $ningen = new Ninja; 
    echo $ningen->getCamo(); 

?>