Define () vs const How do I choose?

Source: Internet
Author: User
Tags php define scalar

Use define () unless you consider readability, class constants, or focus on micro-optimization

1, in PHP is to use the Define () function to define constants, PHP 5.3.0 later, PHP can also use the const keyword to declare constants, once a constant is defined, it can not be changed or de-defined

2. Constants can only contain scalar data (boolean,integer,float, and string). You can define resource constants, but try to avoid them because they cause unpredictable results.

3, you can simply specify its name to obtain a constant value, unlike a variable, you should not precede the constant with the $ symbol. If the constant name is dynamic, you can also use the function constant () to get the value of the constant. Use get_defined_constants () to get a list of all defined constants

Note: Constants and (global) variables are in different namespaces. This means that for example TRUE and $TRUE is different

Constants and variables have the following differences

A constant is not preceded by a dollar sign ($); a constant can only be defined with the Define () function, not by an assignment statement; constants are defined and accessed anywhere, regardless of the scope of the variable; constants cannot be redefined or undefined once defined; The value of a constant can only be scalar.

Define vs Const

1, define () define constants in the execution period, define constants using the const keyword must be at the top of the scope, because this method is defined at compile time , which means that it cannot be within the function, within the loop, and if a const is used to define constants within a statement, so that Const has a slight speed advantage, but it is not worth considering .

2, define () puts constants into the global scope, although you can include namespaces in the constant name, which means you cannot define class constants using define ()

3, define () allows you to use expressions in constant names and constant values, and const does not, which makes define () more flexible

Example

1、constYou cannot use conditional expressions to define constants. If you want to define a global constant, only outside of the expression

if (...) {    Const FOO = ' BAR ';    invalid}//butif (...) {    define (' FOO ', ' BAR ');//valid}

2, const you can use a static scalar (number, string or other constant like true ,, false null , __FILE__ ), and vice versa define() there is no limit. However, you can use a constant expression after PHP 5.6

Const BIT_5 = 1 << 5;    Valid since PHP 5.6, invalid Previouslydefine (' Bit_5 ', 1 << 5); Always valid

3, const use an ordinary constant name 反之define() can use any constant expression

for ($i = 0; $i < + + + $i) {    define (' Bit_ '. $i, 1 << $i);}

4, const总是大小写敏感的 反之define() allows you to define a case insensitive constant through the third argument

Define (' FOO ', ' BAR ', true); Echo FOO; Barecho foo; BAR

5, const simply reads nicer. It's a language construct instead of a function and also are consistent with how are define constants in Classes,const Defi NES a constant in the current namespace, while define () have to is passed the full namespace name:

Namespace a\b\c;//to define the constant a\b\c\foo:const FOO = ' BAR ';d efine (' A\b\c\foo ', ' Bar ');

6, Since PHP 5.6 const Constants can also is arrays, while define() does not support arrays yet. However arrays'll be supported to both cases in PHP 7.

Const FOO = [1, 2, 3];    Valid in PHP 5.6define (' FOO ', [1, 2, 3]); Invalid in PHP 5.6, valid in PHP 7.0

As consts is language constructs and defined at compile time they is a bit faster than define ().

It is the well known, PHP define () is slow when using a large number of constants. People has even invented things like apc_load_constants () and hidef to get around this.

Consts make the definition of constants approximately twice as fast (on development machines with XDebug turned on even MO RE). Lookup time on the other hand does no change (as both constant types share the same lookup table)

Finally, note that const can also is used within a class or interface to define a class constant or interface constant. cannot is used for this purpose:

Class Foo {    const BAR = 2;//valid}//butclass Baz {    define (' Qux ', 2);//Invalid}

Summary

Unless need any type of conditional or expressional definition, use const s instead of define() s-simply for the sake of readability!

<?php//to see how these two methods handle namespacesnamespace middleearth\creatures\dwarves;const gimli_id = 1;define (' MiddleEarth\ Creatures\elves\legolas_id ', 2); Echo (\middleearth\creatures\dwarves\gimli_id);  1echo (\middleearth\creatures\elves\legolas_id);  2; Note: We used define ()//Now let's declare some bit-shifted constants representing ways to enter Mordor.define (' Transport_metho D_sneaking ', 1 << 0); Ok!const transport_method_walking = 1 << 1; Compile error! Const can ' t use expressions as values//next, conditional constant. Define (' hobbits_frodo_id ', 1), if ($isGoingToMordor) {    define (' Transport_method ', transport_method_sneaking);// ok!    Const PARTY_LEADER_ID = hobbits_frodo_id//Compile Error: Const cannot be used in an if block}//Finally, class constants class onering{    const melting_point_degree S = 1000000; ok!    Define (' Show_elvish_degrees ', 200); Compile error: Define () cannot be used within a class}?>

Whichever you choose, be consistent

Take a look at how define is implemented in the kernel

/* {{{proto bool define (string constant_name, mixed value, Boolean case_insensitive=false) define a new constant */zend _function (define) {char *name;int name_len;zval *val;zval *val_free = Null;zend_bool Non_cs = 0;int case_sensitive = CONST_ Cs;zend_constant c;if (Zend_parse_parameters (Zend_num_args () tsrmls_cc, "Sz|b", &name, &name_len, &val, &non_cs) = = FAILURE) {return;} if (non_cs) {case_sensitive = 0;} /* Class constant, check if there is name and do sure class is valid & exists */if (ZEND_MEMNSTR (Name, "::", sizeof ( "::")-1, name + Name_len)) {Zend_error (e_warning, "Class constants cannot be defined or redefined"); Return_false;} Repeat:switch (Z_type_p (val)) {case Is_long:case is_double:case is_string:case is_bool:case is_resource:case IS_NULL: Break;case Is_object:if (!val_free) {if (Z_obj_ht_p (val)->get) {Val_free = val = z_obj_ht_p (val)->get (Val TSRMLS_ CC); goto repeat;} else if (Z_obj_ht_p (val)->cast_object) {alloc_init_zval (val_free); if (z_obj_ht_P (Val)->cast_object (Val, Val_free, is_string tsrmls_cc) = = SUCCESS) {val = Val_free;break;}}} /* No break */default:zend_error (e_warning, "Constants may be evaluate to scalar values"), if (Val_free) {Zval_ptr_dtor (& Amp;val_free);} Return_false;} C.value = *val;zval_copy_ctor (&c.value); if (Val_free) {zval_ptr_dtor (&val_free);} C.flags = case_sensitive; /* Non Persistent */c.name = is_interned (name)? Name:zend_strndup (name, Name_len); if (c.name = = NULL) {return_false;} C.name_len = Name_len+1;c.module_number = Php_user_constant;if (zend_register_constant (&c TSRMLS_CC) = = SUCCESS) { Return_true;} else {return_false;}} /*}}} *//* {{{proto bool defined (string constant_name) Check whether a constant exists */zend_function (defined) {char * Name;int name_len;zval c;if (Zend_parse_parameters (Zend_num_args () tsrmls_cc, "s", &name, &name_len) = = FAILURE ) {return;} if (ZEND_GET_CONSTANT_EX (name, Name_len, &c, NULL, zend_fetch_class_silent tsrmls_cc)) {zval_dtor (&c); ReturN_true;} else {return_false;}} /* }}} */

 const

Zend_api int zend_register_constant (zend_constant *c tsrmls_dc) {char *lowercase_name = Null;char *name;int ret = SUCCESS; ULONG chash = 0; #if 0printf ("Registering Constant for Module%d\n", C->module_number); #endifif (! ( C->flags & Const_cs) {/* Keep in mind that C->name_len already contains the ' */lowercase_name ' = Estrndup (C- >name, c->name_len-1); Zend_str_tolower (Lowercase_name, c->name_len-1); lowercase_name = (char*) zend_new_ Interned_string (Lowercase_name, C->name_len, 1 tsrmls_cc); name = Lowercase_name;chash = is_interned (lowercase_name ) ? Interned_hash (Lowercase_name): 0;} else {char *slash = STRRCHR (c->name, ' \ \ '), if (slash) {lowercase_name = Estrndup (C->name, c->name_len-1); zend_ Str_tolower (Lowercase_name, slash-c->name); lowercase_name = (char*) zend_new_interned_string (Lowercase_name, C- >name_len, 1 tsrmls_cc); name = Lowercase_name;chash = is_interned (lowercase_name)? Interned_hash (Lowercase_name): 0;} else {name = C->name;}} if (chaSH = = 0) {chash = Zend_hash_func (name, C->name_len);} /* Check If the user is trying to define the internal pseudo constant name __compiler_halt_offset__ */if ((C->name_len = = sizeof ("__compiler_halt_offset__") &&!memcmp (name, "__compiler_halt_offset__", sizeof ("__compiler_halt_ Offset__ ")-1) | | Zend_hash_quick_add (EG (zend_constants), name, C->name_len, Chash, (void *) C, sizeof (zend_constant), NULL) ==failure  {/* The internal __compiler_halt_offset__ is prefixed by NULL byte */if (c->name[0] = = ' && ' C->name_len > sizeof ("\0__compiler_halt_offset__") && memcmp (name, "\0__compiler_halt_offset__", sizeof ("\0__ Compiler_halt_offset__ ")) = = 0) {name++;} Zend_error (E_notice, "Constant%s already defined", name), Str_free (C->name); C->flags & const_persistent) {zval_dtor (&c->value);} ret = FAILURE;} if (Lowercase_name &&!is_interned (lowercase_name)) {efree (lowercase_name);} return ret;}

Reference

    • Stack overflow:define () vs. const
    • PHP Manual: Constants
    • Stack overflow:define () vs. variable
    • Test address

Define () vs const How do I choose?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.