024PHP_ Constants - Manual

download 024PHP_ Constants - Manual

of 13

Transcript of 024PHP_ Constants - Manual

  • 7/28/2019 024PHP_ Constants - Manual

    1/13

    [edit] Last updated: Fri, 20 Apr 2012

    Constants

    Table of Contents

    Syntax

    Magic constants

    A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic

    constants, which aren't actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase.

    The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of

    letters, numbers, or underscores. As a regular expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

    Tip

    See also the Userland Naming Guide.

    PHP: Constants - Manual http://www.php.net/manual/en/language.constants.php

    1 of 13 26/04/2012 12:14

  • 7/28/2019 024PHP_ Constants - Manual

    2/13

    1 of 13 26/04/2012 12:14

    Example #1 Valid and invalid constant names

    Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).

    Like superglobals, the scope of a constant is global. You can access constants anywhere in your script without regard to scope. For more information on

    scope, read the manual section on variable scope.

    User Contributed Notes Constants

    Anonymous 27-Aug-2011 07:35

    PHP will allow characters other than those shown for both variable names and constants, and therefore probably functin names, too. And I'm

    pretty sure array indexes also.

    Many others are allowed, while some are not. It seems like a craps-shoot at first, but there is a 'bit' of reason...

    you can do this:

  • 7/28/2019 024PHP_ Constants - Manual

    3/13

  • 7/28/2019 024PHP_ Constants - Manual

    4/13

    I recently found I needed a way of retrieving the value of a constant dynamically - e.g. trying to find the value of FOO_BAR by passing

    'FOO_' . $someVariableWithValueBAR. I came up with the following solution:

    Note the use of strtoupper() as constants should be defined in uppercase for good practice - feel free to remove if you have constants

    defined in lowercase or you can set $changing_variable as uppercase.

    Might be of some use to someone!

    tudor at tudorholton dot com 09-Jul-2007 05:15

    Note that constant name must always be quoted when defined.

    e.g.

    define('MY_CONST','blah') - correct

    define(MY_CONST,'blah') - incorrect

    The following error message also indicates this fact:Notice: Use of undefined constant MY_CONST - assumed 'MY_CONST' in included_script.php on line 5

    Note the error message gives you some incorrect information. 'MY_CONST' (with quotes) doesn't actually exist anywhere in your code. The

    error _is_ that you didn't quote the constant when you defined it in the 'assumed' file.

    Andreas R. 30-Apr-2007 07:19

    If you are looking for predefined constants like

    PHP: Constants - Manual http://www.php.net/manual/en/language.constants.php

    4 of 13 26/04/2012 12:14l h // h / l/ /l h

  • 7/28/2019 024PHP_ Constants - Manual

    5/13

    * PHP_OS (to show the operating system, PHP was compiled for; php_uname('s') might be more suitable),

    * DIRECTORY_SEPARATOR ("\\" on Win, '/' Linux,...)

    * PATH_SEPARATOR (';' on Win, ':' on Linux,...)

    they are buried in 'Predefined Constants' under 'List of Reserved Words' in the appendix:

    http://www.php.net/manual/en/reserved.constants.php

    while the latter two are also mentioned in 'Directory Functions'

    http://www.php.net/manual/en/ref.dir.php

    pdenny at magmic dot com 18-Feb-2007 09:46

    Note that constants can also be used as default argument values

    so the following code:

    will produce :

    Passing constants as default values Works!

    (I tried this in both PHP 4 and 5)

    dexen at google dot me dot up 05-Sep-2006 04:02

    1) Constants are invaluable when you want to be sure that *nobody* changes your important piece of data through lifetime of script --

    especially when you're developing in team -- as this can cause strange, hard to track bugs.

    2) Using constants is prefered over ``magic values'', as it leads to self-documenting code. Also saves you from scanning and tweaking tensof files should the value ever change.

    Consider example:

    versus:

    In response to ``kencomer'':

    PHP: Constants - Manual http://www.php.net/manual/en/language.constants.php

    5 of 13 26/04/2012 12:14PHP C M l h // h / l/ /l h

  • 7/28/2019 024PHP_ Constants - Manual

    6/13

    3) Why not to use

    and comment one of them out as needed when developing/deploying?

    That'd save a lot of ugly ``if ( defined( 'DEBUG' ) && DEBUG ) {}''.

    4) For debugging toggled on/off you pretty often want to use assert() anyway. You're free to turn it on/off at any moment (thou you better

    do it only once ;) ). assert() gives some nice details upon failed assertion, like file/line/function and context (that's invaluable!)

    martin at larsen dot dk 23-Feb-2006 02:24

    I find variables much more flexible than constants because variables can be used inside quotes and heredocs etc. Especially for language

    systems, this is nice.

    As stated in one of the previous notes, there is no speed penalty by using variables. However, one issue is that you risc name collision

    with existing variables. When implementing a language system I simply found that adding a prefix to all the variables was the way to go,

    for example:

    $LNG_myvar1 = "my value";

    That is easier and performs faster than using arrays like

    $LNG['myvar'] = "my value";

    As a final note, implementing a new superglobal in PHP would make using constants much more beneficial. Then it could be used in qoutes

    like this:

    "The constant myconst has the value $CONSTANTS[myconst] !"

    anj at aps dot anl dot gov 20-Dec-2005 08:42

    It is possible to define constants that have the same name as a built-in PHP keyword, although subsequent attempts to actually use these

    constants will cause a parse error. For example in PHP 5.1.1, this code

    gives the error

    PHP: Constants - Manual http://www.php.net/manual/en/language.constants.php

    6 of 13 26/04/2012 12:14PHP C t t M l htt // h t/ l/ /l t t h

  • 7/28/2019 024PHP_ Constants - Manual

    7/13

    Parse error: syntax error, unexpected T_PUBLIC in test.php on line 3

    This is a problem to be aware of when converting PHP4 applications to PHP5, since that release introduced several new keywords that used to

    be legal names for constants.

    kencomer at NOSPAM dot kencomer dot com 14-Sep-2005 05:38

    Being a belt and suspenders person, when I use a constant to do flow control (i.e., using constants to determine which version of a section

    of the program should be used), I always use something like:

    if ( defined('DEBUG') && TRUE===DEBUG )

    If you accidentally use DEBUG somewhere before it is defined, PHP will create a new constant called DEBUG with the value 'DEBUG'. Adding

    the second comparison will prevent the expression from being TRUE when you did not intentionally create the constant. For the constant

    DEBUG, this would rarely be a problem, but if you had (e.g.) a constant used to determine whether a function was created using

    case-sensitive comparisons, an accidental creation of the constant IGNORE_CASE having the value 'IGNORE_CASE' could drive you up the wall

    trying to find out what went wrong, particularly if you had warnings turned off.

    In almost all code I write, I put this function definition in my configuration section:

    Then, in my code, I'll sprinkle liberal doses of debug code like :

  • 7/28/2019 024PHP_ Constants - Manual

    8/13

    debug_print( "new instance of Example created with '$whatever'\n",DEBUG_TRACK_EXAMPLE_CREATION);

    }

    }

    ?>

    and :

    In the first case, I would not want to see that message every time I went into DEBUG mode, so I made it a special case. The second case is

    always printed in DEBUG mode. If I decide to turn everything on, special cases and all, all I have to do is comment out the "if" line in

    debug_print() and presto magicko! It costs a little and gains a lot.

    As another belt-and-suspenders aside, notice that, unlike most people, I put the language constant (e.g.,TRUE, "string", etc.) on the left

    side of the comparison. By doing that, you can never accidentally do something like

    if ( $hard_to_find_error="here" )

    because you always write it as

    if ( "here"==$no_error )

    or, if you got it wrong,

    if ( "here"=$easy_to_find_parse_error )

    Angelina Bell 25-Jul-2005 12:39

    It is so easy to create a constant that the php novice might do so accidently while attempting to call a function with no arguments. For

    example:

  • 7/28/2019 024PHP_ Constants - Manual

    9/13

    ?>

    OOPS! I don't notice my typo, the SessionCheck function

    doesn't work, and it takes me all afternoon to figure out why not!

    hafenator2000 at yahoo dot com 21-Apr-2005 02:09

    PHP Modules also define constants. Make sure to avoid constant name collisions. There are two ways to do this that I can think of.

    First: in your code make sure that the constant name is not already used. ex. This can get messy when you start thinking about collision handling, and the implications of

    this.

    Second: Use some off prepend to all your constant names without exception ex.

    Perhaps the developers or documentation maintainers could recommend a good prepend and ask module writers to avoid that prepend in modules.

    storm 18-Apr-2005 09:54

    An undefined constant evaluates as true when not used correctly. Say for example you had something like this:

    settings.php

    test.php

    If for some reason settings.php doesn't get included and the DEBUG constant is not set, PHP will STILL print the sensitive data. The

    solution is to evaluate it. Like so:

    PHP: Constants - Manual http://www.php.net/manual/en/language.constants.php

    9 of 13 26/04/2012 12:14 PHP: Constants Manual http://www php net/manual/en/language constants php

  • 7/28/2019 024PHP_ Constants - Manual

    10/13

    settings.php

    test.php

    Now it works correctly.

    kumar at farmdev 25-Oct-2003 05:59

    before embarking on creating a language system I wanted to see if there was any speed advantage to defining language strings as constantsvs. variables or array items. It is more logical to define language strings as constants but you have more flexibility using variables or

    arrays in your code (i.e. they can be accessed directly, concatenated, used in quotes, used in heredocs whereas constants can only be

    accessed directly or concatenated).

    Results of the test:

    declaring as $Variable is fastest

    declaring with define() is second fastest

    declaring as $Array['Item'] is slowest

    =======================================

    the test was done using PHP 4.3.2, Apache 1.3.27, and the ab (apache bench) tool.

    100 requests (1 concurrent) were sent to one php file that includes 15 php files each containing 100 unique declarations of a languagestring.

    Example of each declaration ("Variable" numbered 1 - 1500):

  • 7/28/2019 024PHP_ Constants - Manual

    11/13

    ?>

    Here are the exact averages of each ab run of 100 requests (averages based on 6 runs):

    variable (24.956 secs)

    constant (25.426 secs)

    array (28.141)

    (not huge differences but good to know that using variables won't take a huge performance hit)

    PHP: Constants - Manual http://www.php.net/manual/en/language.constants.php

    11 of 13 26/04/2012 12:14 PHP: Constants - Manual http://www php net/manual/en/language constants php

  • 7/28/2019 024PHP_ Constants - Manual

    12/13

    ewspencer at industrex dot com 18-Aug-2003 06:30

    I find using the concatenation operator helps disambiguate value assignments with constants. For example, setting constants in a global

    configuration file:

    Later, I can use the same convention when invoking a constant's value for static constructs such as require() calls:

    as well as dynamic constructs, typical of value assignment to variables:

    The above convention works for me, and helps produce self-documenting code.

    -- Erich

    katana at katana-inc dot com 25-Feb-2002 11:53

    Warning, constants used within the heredoc syntax (http://www.php.net/manual/en/language.types.string.php) are not interpreted!

    Editor's Note: This is true. PHP has no way of recognizing the constant from any other string of characters within the heredoc block.

    tom dot harris at home dot com 04-Aug-2000 05:44

    To get a full path (the equivalent of something like "__PATH__") use

    dirname($SCRIPT_FILENAME)

    to get the directory name of the called script and

    PHP: Constants Manual http://www.php.net/manual/en/language.constants.php

    12 f 13 26/04/2012 12 14 PHP: Constants - Manual http://www php net/manual/en/language constants php

  • 7/28/2019 024PHP_ Constants - Manual

    13/13

    dirname(__FILE__)

    to get the directory name of the include file.

    Copyright 2001-2012 The PHP GroupAll rights reserved.

    PHP: Constants Manual http://www.php.net/manual/en/language.constants.php