简体   繁体   中英

why is This method constant() in php is giving me warning

const MyConstant = "test";
$declaredcons = "MyConstant";
echo constant ($declaredcons);//Emits me warning why???
echo constant ("MyConstant");//How ever not working 
echo MyConstant;//Outputs test .I dont want to use this...

Iam trying to know why it is giving me warning when i const(constantname).Can any one has tried it .Iam using 5.3.6 on windows 7. Is It bug?

You should only use const inside an CLASS . outside classes it is prefered to use define() Try something like this :

define("MyConstant", "test");

$declaredcons = "MyConstant";

echo constant ($declaredcons); // result : test
echo constant ("MyConstant");  // result : test
echo MyConstant;               // result : test

Inside a class you CAN use const :

class MyClass
{
    const constant = 'constant value';

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

$class = new MyClass();
$class->showConstant();

http://us3.php.net/constant

Take a look at this page. The warning you are seeing is indicating that the constant is not properly declared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM