Alex Ruhl
Alex Ruhl

Reputation: 457

unset or change a defined constant PHP

assumed i define a variable like this:

<?php
define("page", "actual-page");
?>

now i have to change this content from actual-page to second-page how can i realize that?

i try the following methods:

<?php
// method 1
    page = "second-page";

// method 2
    define("page", "second-page");

// method 3
    unset(page);
    define("page", "second-page");
?>

now my ideas goes out... what can i do else?

Upvotes: 10

Views: 41954

Answers (4)

Mihai Pop
Mihai Pop

Reputation: 65

Maybe a very late answer, but the question was "now my ideas goes out... what can i do else?"

Here is what you can do "else" - use $GLOBALS:

<?php
// method 1
    $GLOBALS['page'] = 'first-page';

// method 2
    $GLOBALS['page'] = "second-page";

// method 3
    $GLOBALS['page'] = 'third-page';
?>

I hope it helps. I use it when I do imports and I want specific events not to be fired if the import flag is on for example :)

Upvotes: 4

Shudmeyer
Shudmeyer

Reputation: 352

define has a third argument (boolean) which override the first defined constant to the second defined constant. Setting the first defined constant to true.

<?php
define("page", "actual-page", true);
// Returns page = actual-page

define("page", "second-page");
// Returns page = second-page
?>

Upvotes: -16

Cobra_Fast
Cobra_Fast

Reputation: 16111

You can, with the runkit PECL extension:

runkit_constant_remove('page');

http://php.net/runkit_constant_remove
http://github.com/zenovich/runkit

sudo pecl install https://github.com/downloads/zenovich/runkit/runkit-1.0.3.tgz

Update: This module seems to cause trouble with various other things, like the session system for example.

Upvotes: 6

Juan Pablo Rinaldi
Juan Pablo Rinaldi

Reputation: 3504

When you use PHP's define() function, you're not defining a variable, you're defining a constant. Constants can't have their value modified once the script starts executing.

Upvotes: 21

Related Questions