Creating Constants


Sometimes you don't want variables to be variableyou want their value to be fixed. For example, say you have a variable named $pi that holds the value of pi. It's possible that such a value may be inadvertently modified, which is not good. The solution is to create a constant, whose value can't be altered.

You create constants with the define function, giving it the name of the constant and the value you want to assign to it like this: define ("pi", 3.1415926535);. The name of the constant is always quoted, but the value you assign to the constant is only quoted if it's a string. Take a look at phpconstants.php in Example 1-8, which creates the constant named pi and displays itnote that when you use the constant, you don't prefix it with a $. The results of this example appear in Figure 1-11.

Example 1-8. Creating constants
 <HTML>     <HEAD>         <TITLE>             Using PHP constants         </TITLE>     </HEAD>     <BODY>         <H1>             Using PHP constants         </H1>         <?php             define ("pi", 3.1415926535);             echo "The constant pi holds " , pi,  "<BR>";         ?>     </BODY> </HTML> 

Figure 1-11. Using constants.


If you try to alter the value of this constant (like this: pi = 3.14), PHP won't accept it and won't even start the script.

Because you don't prefix constants with a $, PHP can become confused if you use a constant with the same name as one of the reserved keywords in PHP. These keywords appear in the following list:

PHP Keywords

__CLASS__

__FILE__

__FUNCTION__

__LINE__

__METHOD__

and

default

endif

global

print

array

die

endswitch

if

require

as

do

endwhile

include

require_once

break

echo

Eval

include_once

return

case

else

exception

isset

static

cfunction

elseif

Exit

list

switch

class

empty

extends

new

unset

const

enddeclare

For

old_function

use

continue

endfor

foreach

or

while

declare

endforeach

function

php_user_filter

xor


Also, a number of predefined constants are available to your scripts. We'll use these constants as we need them. Here's a sample:

__LINE__

The current line number of the file.

__FILE__

The full path and filename of the file.

__FUNCTION__

The function name. (This was added in PHP 4.3.0.)

__CLASS__

The class name. (This was added in PHP 4.3.0.)

__METHOD__

The class method name. (This was added in PHP 5.0.0.)

PHP_VERSION

The PHP version.

PHP_OS

The operating system.

DEFAULT_INCLUDE_PATH

Where PHP will search for what it needs.


For example, using echo __LINE__ at a particular position in a script will display the current line that's executing.



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net