Page 1 of 1

Is variable defined?

Posted: Tue May 16, 2006 9:21 pm
by Benjamin
If I have code like this...

Code: Select all

define('ThisConstant', 'ThisValue');

$ThisVariable = 'ThisConstant';

if ('A constant exists named ThisConstant') {
  echo 'ThisConstant';
} else {
  // blah
}
How do I test $ThisVariable to see if a constant with that name exists.

Posted: Tue May 16, 2006 9:26 pm
by Benjamin
Well I dug around in the manual, I guess this will work..

Code: Select all

$ThisPage = strolower(basename($_SERVER['PHP_SELF']));

if (defined($ThisPage)) {
  $PageTitle = constant($ThisPage);
} else {
  $PageTitle = DEFAULT_PAGE_TITLE;
}

Posted: Tue May 16, 2006 10:58 pm
by bdlang
I'd just like to mention that you don't access the value in a constant by surrounding it with quotes. That is a string literal. A contstant would be acccessed like

Code: Select all

define('SOME_CONSTANT', 'this value');
echo SOME_CONSTANT; // this value
PHP Manual: Constants

Posted: Wed May 17, 2006 4:47 am
by Maugrim_The_Reaper
Think he's aware of that - simply laying out logic not code. Yep, the solution should work fine.