1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2016
    Lakewood, WA
    Rep Power

    Questions about Constants

    Two parts to this question...

    One: When defining constants, what is the difference between
    PHP Code:
    define("SOMETHING""Blaw, blaw, blaw");
    PHP Code:
    const SOMETHING 'Blaw, blaw, blaw';
    Second: What is the preferred method of inclusion?

    a) As an included file; or
    b) As an included class...

    Each script that I am thinking about has constants that need to be editable in an "admin" mode, thus I intend to implement this by having a writable file (class or otherwise) where the "admin" script will open it, locate the appropriate line of code, and changes some values.

    Examples I have seen involving a class use the second form, and the PHP documentation seems to indicate the use of const in a class.
  2. #2
  3. Confusing Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Washington, USA
    Rep Power
    define() is a fully dynamic way of creating constants: the name is a string so you could build that at runtime (but I can't imagine a good reason to do so) and the value can be any expression to be evaluated, possibly including variables or function calls.
    PHP Code:
    define("HOSTNAME"gethostname()); // allowed 
    Non-class const is more restrictive: the name is a token in code (not a string) and the value must itself be a constant value (string, int, etc.) or a constant expression.
    PHP Code:
    const HOSTNAME gethostname(); // not allowed
    const THREE 2// constant expressions are allowed 
    Unless you need to use a dynamic value, const is better than define().

    Class-level const is the same concept as the non-class const but works differently: using the same rules, it defines a constant as if a static member of a class. This is more appropriate when you have a constant that is specific to a particular class and so should not be defined at a global level.
    PHP Code:
    class HasAConstant {

    FOO "bar";


    FOO// undefined global constant
    echo HasAConstant::FOO// bar 
    Last edited by requinix; March 19th, 2017 at 05:25 PM.

IMN logo majestic logo threadwatch logo seochat tools logo