Is variable defined?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Is variable defined?

Post 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.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post 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;
}
bdlang
Forum Contributor
Posts: 395
Joined: Tue May 16, 2006 8:46 pm
Location: Ventura, CA US

Post 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
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post by Maugrim_The_Reaper »

Think he's aware of that - simply laying out logic not code. Yep, the solution should work fine.
Post Reply