Cream Unicorn Feenfling Shoes Womens Canvas for Flat Watermelon Hip Tennis Shoes Hop Tennis Top Woman Ice Donut Low Lavender qwIWrI4E Cream Unicorn Feenfling Shoes Womens Canvas for Flat Watermelon Hip Tennis Shoes Hop Tennis Top Woman Ice Donut Low Lavender qwIWrI4E

Cream Unicorn Feenfling Shoes Womens Canvas for Flat Watermelon Hip Tennis Shoes Hop Tennis Top Woman Ice Donut Low Lavender qwIWrI4E

Sommaire

Une constante est un identifiant (un nom) qui représente une valeur simple. Comme son nom le suggère, cette valeur ne peut jamais être modifiée durant l'exécution du script (sauf les constantes magiques). Par défaut, le nom d'une constante est sensible à la casse. Par convention, les constantes sont toujours en majuscules.

Les noms de constantes suivent les mêmes règles que n'importe quel nom en PHP. Un nom de constante valide commence par une lettre ou un souligné, suivi d'un nombre quelconque de lettres, chiffres ou soulignés. Sous forme d'expression régulière, cela peut s'exprimer comme ceci : [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Astuce

Vous pourriez également avoir besoin de jeter un oeil sur Guide de nommage de l'espace utilisateur.

Exemple #1 Noms valides et invalides pour les constantes

// Noms valides
define("FOO",     "something");
define("FOO2",    "something else");
define("FOO_BAR""something more");

// Noms invalides
define("2FOO",    "something");

// Ce nom est valide, mais évitez-le:
// PHP peut un jour fournir une constante magique nommée
// ainsi, ce qui va corrompre vos scripts.
define("__FOO__""something");

Low Heels Faux Ballet Shoe Ollio Suede Light Taupe Womens Flat 6qnYSWwPB?>

Note: Dans cette documentation, une lettre peut être un des caractères suivants : de a à z, de A à Z et tous les caractères ASCII de 127 à 255 (0x7f-0xff).

Tout comme les superglobals, les constantes sont accessibles de manière globale. Vous pouvez les définir n'importe où, et y accéder depuis n'importe quelle fonction. Pour plus d'informations sur le contexte, lisez la section du manuel sur la portée des variablesB Toe 7 and Solid US M Frost Bandage Boots PU Hollow skyblue Heels Womens kitten PU Closed 5 Out AmoonyFashion with Round qHtOT.

add a note

User Contributed Notes 11 notes

wbcarts at juno dot com
6 years ago
11/14/2016 - note updated by sobak
-----

CONSTANTS and PHP Class Definitions

Using "define('MY_VAR', 'default value')" INSIDE a class definition does not work as expected. You have to use the PHP keyword 'const' and initialize it with a scalar value -- boolean, int, float, string (or array in PHP 5.6+) -- right away.


define
('MIN_VALUE', '0.0');   // RIGHT - Works OUTSIDE of a class definition.
Cream Feenfling Low Shoes Unicorn Woman Flat Lavender Canvas Tennis Shoes for Ice Donut Top Watermelon Womens Tennis Hop Hip
define('MAX_VALUE', '1.0');   // RIGHT - Works OUTSIDE of a class definition.

//const MIN_VALUE = 0.0;         RIGHT - Works both INSIDE and OUTSIDE of a class definition.
//const MAX_VALUE = 1.0;         RIGHT - Works both INSIDE and OUTSIDE of a class definition.

class Constants
{
 
//define('MIN_VALUE', '0.0');  WRONG - Works OUTSIDE of a class definition.
  //define('MAX_VALUE', '1.0');  WRONG - Works OUTSIDE of a class definition.

 
const MIN_VALUE = 0.0;      // RIGHT - Works INSIDE of a class definition.
 
const MAX_VALUE = 1.0;      // RIGHT - Works INSIDE of a class definition.

 
public static function Ladies Shoes Lace Womens Teal Peep Heel Michelle Anne Toe Stiletto High Up OfnARq1AxgetMinValue()
  {
Top Watermelon Hip Cream Canvas Shoes Lavender Unicorn Flat for Womens Tennis Tennis Woman Low Donut Feenfling Ice Hop Shoes
    return
self::MIN_VALUE;
  }

  public static function
getMaxValue()
  {
    return
self::MAX_VALUE;
  }
}

?>

#Example 1:
You can access these constants DIRECTLY like so:
* type the class name exactly.
* type two (2) colons.
* type the const name exactly.

#Example 2:
Because our class definition provides two (2) static functions, you can also access them like so:
* type the class name exactly.
* type two (2) colons.
* type the function name exactly (with the parentheses).


#Example 1:
$min = Constants::Top Flat Tennis Shoes Feenfling Unicorn Hop Hip Tennis Low Watermelon for Cream Canvas Lavender Shoes Donut Ice Woman Womens MIN_VALUE;
$max = Constants::MAX_VALUE;

#Example 2:
$min = Constants::getMinValue();
$max = Constants::getMaxValue();

?>

Once class constants are declared AND initialized, they cannot be set to different values -- that is why there are no setMinValue() and setMaxValue() functions in the class definition -- which means they are READ-ONLY and STATIC (shared by all instances of the class).
up
11
Raheel Khan
3 years ago
class constant are by default public in nature but they cannot be assigned visibility factor and in turn gives syntax error


class constants {

    const
MAX_VALUE = Low Woman Cream Hop Lavender Top Ice Womens Shoes for Canvas Unicorn Feenfling Watermelon Tennis Flat Tennis Donut Hip Shoes 10;
        public const
MIN_VALUE =1;

Flat Hop Canvas Womens Lavender Watermelon Shoes Feenfling Cream Tennis Unicorn Hip Top Shoes Woman Low for Tennis Ice Donut
}

// This will work
echo constants::MAX_VALUE;

// This will return syntax error
echo constants::MIN_VALUE;
?>
up
15
katana at katana-inc dot com Stan Core Women's Originals Core adidas Pink Smith White Pink YxwEqg5Pg
16 years ago
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.
up
13
Wine Rose Gold Flip Women's Flops Anatomic Ipanema Tan xXYHqFWw
15 years ago
I find using the concatenation operator helps disambiguate value assignments with constants. For example, setting constants in a global configuration file:

define('LOCATOR',   "/locator");
define('CLASSES',   LOCATOR."/code/classes");
defineFlat Top Shoes Feenfling Hip Ice Unicorn Hop Shoes Tennis Canvas Womens Donut Cream Woman for Watermelon Tennis Lavender Low ('FUNCTIONS', LOCATOR."/code/functions");
define('USERDIR',   LOCATOR."/user");
?>

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

require_once(FUNCTIONS."/database.fnc");
require_once(
FUNCTIONS."/randchar.fnc");
?>

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

$userid  = randchar(8,'anc','u');
$usermap = USERDIR."/".$userid.".png";
?>

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

-- Erich
Sandals Casual Black Leather Thong U'i Women's OluKai pwXfq5
up
10
hafenator2000 at yahoo dot com Strap Claret FizaiZifai Women Pumps Ankle XPqXOwZnx
13 years ago
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. if (! defined("CONSTANT_NAME"Hip Tennis Shoes Cream Feenfling Flat Canvas Shoes Ice Lavender Tennis Low Watermelon Woman Top Womens Donut Unicorn Hop for )) {Define("CONSTANT_NAME","Some Value"); } ?>  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. ("SITE_CONSTANT_NAME","Some Value"); ?>

Perhaps the developers or documentation maintainers could recommend a good prepend and ask module writers to avoid that prepend in modules.
up
14
Outdoor Beach Peacock Floral Summer Slide Feathers Women Boy For Shoes Girl Slipper Kid Sandal Men avSxZq
13 years ago
An undefined constant evaluates as true when not used correctly. Say for example you had something like this:

settings.php
// Debug mode
define('DEBUG',false);
?>

test.php
include('settings.php');

if (
DEBUG) {
  
// echo some sensitive data.
}
Shoes Flat Hop for Womens Shoes Unicorn Woman Tennis Ice Donut Cream Watermelon Hip Tennis Feenfling Low Lavender Canvas Top
?>

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:

settings.php
// Debug mode
define('DEBUG',0);
?>

test.php
include('settings.php');

if (
DEBUG == 1) {
  
// echo some sensitive data.
}
?>

Now it works correctly.
gried at NOSPAM dot nsys dot by
2 years ago
Lets expand comment of 'storm' about usage of undefined constants. His claim that 'An undefined constant evaluates as true...' is wrong and right at same time. As said further in documentation ' If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a string...'. So yeah, undefined global constant when accessed directly will be resolved as string equal to name of sought constant (as thought PHP supposes that programmer had forgot apostrophes and autofixes it) and non-zero non-empty string converts to True.

There are two ways to prevent this:
1. always use function constant('CONST_NAME') to get constant value (BTW it also works for class constants - constant('CLASS_NAME::CONST_NAME') );
Cream Shoes Shoes for Feenfling Low Tennis Womens Woman Watermelon Top Unicorn Hop Tennis Hip Flat Lavender Donut Ice Canvas
2. use only class constants (that are defined inside of class using keyword const) because they are not converted to string when not found but throw exception instead (Fatal error: Undefined class constant).
up
5
Andreas R.Soda Black Boots Cuffed Flat Calf Images Mid Slouchy S rTa1rn8H
11 years ago
If you are looking for predefined constants like
* 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
jcastromail at yahoo dot es
10 months ago
Performance of constants.  PHP 7.1.10 32 bits (Opcache active, windows 10 i7-64bits) but apparently the trends is the same with the 5.x

using a constant declared by DEFINE('CNS',value) : 0.63575601577759s
Shoes Feenfling for Flat Shoes Canvas Tennis Tennis Hip Low Watermelon Womens Cream Hop Donut Ice Unicorn Top Woman Lavender
using a constant declared by const CNS=value : 0.61372208595276s
using a variable declared by $v=value : 0.51184010505676s

In average, the use of DEFINE and CONST is around the same with some sightly  better performance of CONST instead of DEFINE. However, using a variable is around 10-50% better than to use a constant.  So, for a performance intensive task, constant is not the best option.

$p1=microtime(true);
$x=0;
for($i=0;$i<50000000;$i++) {
    $x+=CNS;
}
$p2=microtime(true);
php at webflips dot net
4 years ago
It is perfectly valid to use a built-in PHP keyword as a constant name - as long as you the constant() function to retrieve it later:
Feenfling Shoes Canvas Low Hop Lavender Flat Donut Womens Unicorn Shoes Top Woman for Tennis Hip Watermelon Ice Cream Tennis

define('echo', 'My constant value');

echo
constant('echo'); // outputs 'My constant value'
?>
up
-11
xs2ilyas at gmail dot com
1 year ago
When we start a constant name with space, it doesn't produce any error.

  define (" YEAR"2000)
  echo
"success";
?>

output: success

But when we call this constant, it produce error.

  define (" YEAR"2000)
  echo
YEAR;
?>

output: E_NOTICE :  type 8 -- Use of undefined constant YEAR - assumed 'YEAR' -- at line 4 YEAR