Changes

Jump to: navigation, search

PHP Constants

1,186 bytes added, 14:40, 29 May 2007
Using a Variable as a Constant Name
== Using a Variable as a Constant Name ==
 
It is not always the case that you want to ''hard-code'' a constant name into a script at the point you wish to access it. Perhaps in your script you need to store the name of the constant in a variable. How then, would you access the value assigned to that constant. The answer is to use the PHP ''constant()'' fucntion. The ''constant()'' function takes the namer of the constant as an argument and returns the value of the constant which matches that name. The key point to understand here as that the argument passed through to ''constant()'' can be a string variable set to the name of the constant.
 
As always an example helps a great deal in understanding a concept. In the script below we define a constant called ''MY_CONSTANT''. We create a string variable called constantName and assign it a value of ''MY_CONSTANT''. We can then use this new variable as the argumen to ''constant()'' to obtain the constant value of ''MY_CONSTANT'':
 
<pre>
<?php
define ('MY_CONSTANT', "This is a constant string.");
$constantName = 'MY_CONSTANT';
 
if (defined ( $constantName ))
{
echo constant($constantName);
}
else
{
echo "$constantName constant is not defined.";
?>
</pre>
== Predefined PHP Constants ==

Navigation menu