Someone
Someone

Reputation: 10575

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?

Upvotes: 1

Views: 4552

Answers (2)

DonSeba
DonSeba

Reputation: 2119

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();

Upvotes: 1

Bueller
Bueller

Reputation: 2344

https://www.php.net/constant

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

Upvotes: 0

Related Questions