Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override an existing defined constant [duplicate]

Tags:

php

Possible Duplicate:
Can you assign values to constants with equal sign after using defined in php?

I'm not sure if it's just me, but how do you override an existing constant something like this:

define('HELLO', 'goodbye');
define('HELLO', 'hello!');

echo HELLO; <-- I need it to output "hello!"

//unset(HELLO); <-- unset doesn't work
//define('HELLO', 'hello!'); 
like image 673
MacMac Avatar asked Mar 02 '11 01:03

MacMac


People also ask

How to override define constant in PHP?

If the page is reloading, you can have a dynamic value change the constant. Like: $random = something_that_gives_me_randomness(); define('HELLO', $random); But if you are trying to change a constant in the same script, then linepogl is correct.

Can you redefine a constant?

No, you cannot redefine a constant (except with runkit_constant_redefine), that's why is called CONSTANT.

What are the ways to define a constant in PHP?

A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined. To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name.


2 Answers

Truth is, you can, but you should not. PHP being an interpreted language, there is nothing you "can't" do. The runkit extension allow you to modify PHP internals behavior, and provide the runkit_constant_redefine(simple signature) function.

like image 54
131 Avatar answered Sep 25 '22 13:09

131


You can override a constant if it extended from a class. So in your case you can't override constant as it consider came from a same class. ie (taken from php manual):

<?php

class Foo {
    const a = 7;
    const x = 99;
}

class Bar extends Foo {
    const a = 42; /* overrides the `a = 7' in base class */
}

$b = new Bar();
$r = new ReflectionObject($b);
echo $r->getConstant('a');  # prints `42' from the Bar class
echo "\n";
echo $r->getConstant('x');  # prints `99' inherited from the Foo class

?>

If you turn on php error reporting ie:

ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);

you will see a notice like

Notice: Constant HELLO already defined in ....
like image 28
Gajahlemu Avatar answered Sep 25 '22 13:09

Gajahlemu