Php constant usage in the PHP Getting Started Tutorial

Source: Internet
Author: User
Constants are a very new data type in php. I will introduce some usage of PHP constants in detail for beginners. if you need to know them, refer to the PHP constant define () function.

Constants are a very new data type in php. I will introduce some usage of PHP constants in detail for beginners. For more information, see.

PHP constants

The define () function is used to define constants. once a constant is defined, it cannot be changed or canceled.

The instance code for defining constants is as follows:

  1. Define ("CONSTANT", "Hello! ");
  2. Echo CONSTANT;
  3. ?>

Constant names and any other PHP labels follow the same naming rules. valid constant names start with letters or underscores followed by any letters, numbers or underscores.

Constants are case-sensitive by default, and constant identifiers are always capitalized. The value cannot be changed during script execution. differences between defining constants and defining variables:

1. there is no dollar sign before the constant ($)

2. constants can only be defined using the define () function, but not through the value assignment statement.

3. constants can be defined and accessed anywhere regardless of the variable range rules.

4. once defined, constants cannot be redefined or undefined.

5. the constant value can only be a scalar.

PHP has a large number of predefined constants built in. you can search for the PHP Manual on the Internet for specific content.

Determines whether a constant has been defined.

How to determine whether a php constant has been defined, suddenly confused, dizzy, specially checked the manual, the record filing summary results are as follows:

(1) determine whether a constant exists

The instance code is as follows:

  1. If (defined ('myconstant ')){
  2. Echo MYCONSTANT;
  3. }

(2) determine whether a variable is defined

The instance code is as follows:

  1. If (isset ($ myvar )){
  2. Echo "variable $ myvar .";
  3. 3}

(3) determine whether a function exists

The instance code is as follows:

Differences between constants and variables:

1: constants are globally valid, so on the page, within the function, the class or even the array can be directly referenced.

The instance code is as follows:

  1. $ A = 66;
  2. Function t () {echo $ ;}
  3. T (); // at this time, 99 cannot be printed because of the impact of function scope. to print 99, you can change it:
  4. Define ("A", 66 );
  5. Function t () {echo ;}
  6. T ();

2: once a constant is defined, it cannot be redefined. it cannot be cleared or modified. constants can also be dynamic.

The instance code is as follows:

  1. Define ("A", "constant introduction ");
  2. Define ("B", "constant Dynamic Call ");
  3. $ C = $ _ get ['c']; // The value of B is directly parsed as a constant name.
  4. Echo constant ($ c); // constant (constant name) ---> returns the value of a constant.

Const, a constant modifier commonly used in object-oriented const constant modifiers. we know that defining constants in PHP is done through the define () function, but defining constants in the class cannot use define (), but the const modifier must be used. after a constant in a class is defined by const, its access method is similar to that of a static member. it is accessed by the class name or by using self in the Member method, however, PHP 5.3.0 and later versions can also be accessed using objects. A constant defined by const cannot be assigned a value again. if you try to change its value in a program, an error will occur.

The instance code is as follows:

  1. Class MyClass {
  2. Const CONSTANT = 'constant value'; // use const to declare a CONSTANT and assign it to the initial value.
  3. Function showConstant (){
  4. Echo self: CONSTANT ."
    "; // Use self to access constants. do not add" $ "before constants"
  5. }
  6. }
  7. Echo MyClass: CONSTANT ."
    "; // Use the class name to access the constant outside the class, and do not add" $"
  8. $ Class = new MyClass ();
  9. $ Class-> showConstant ();
  10. Echo $ class: CONSTANT; // after PHP 5.3.0
  11. ?>

Follow-up details: You do not need to use the "$" symbol before using the constant name defined by const, and the constant name is usually in uppercase.

An error occurs when you try to assign a value to a constant defined by const.

The instance code is as follows:

  1. Class MyClass {
  2. Const CONSTANT = 'constant value ';
  3. Function setCONSTANT (){
  4. Self: CONSTANT = 'news constant'; // the program running result will be incorrect.
  5. }
  6.                                                                                                                                                                                          
  7. }
  8. Echo MyClass: CONSTANT;
  9.                                                                                                                                                                             
  10. ?>
  11.  
  12. CONSTANTS and PHP Class Definitions
  13. Using "define ('My _ var', 'default value')" INSIDE a class definition does not work. you have to use the PHP keyword 'const' and initialize it with a scalar value -- boolean, int, float, or string (no array or other object types) -- right away.

You cannot use "define ('My _ var', 'default value')" in the class to define constants. you must use the PHP keyword 'const' to initialize a scalar-boolean, int, float, or string (except for arrays and other object types ),

The instance code is as follows:

  1. Define ('min _ value', '0. 0'); // RIGHT-Works OUTSIDE of a class definition.
  2. Define ('max _ value', '1. 0'); // RIGHT-Works OUTSIDE of a class definition.
  3. // Const MIN_VALUE = 0.0; WRONG-Works INSIDE of a class definition.
  4. // Const MAX_VALUE = 1.0; WRONG-Works INSIDE of a class definition.
  5. Class Constants
  6. {
  7. // Define ('min _ value', '0. 0'); WRONG-Works OUTSIDE of a class definition.
  8. // Define ('max _ value', '1. 0'); WRONG-Works OUTSIDE of a class definition.
  9. Const MIN_VALUE = 0.0; // RIGHT-Works INSIDE of a class definition.
  10. Const MAX_VALUE = 1.0; // RIGHT-Works INSIDE of a class definition.
  11. Public static function getMinValue ()
  12. {
  13. Return self: MIN_VALUE;
  14. }
  15. Public static function getMaxValue ()
  16. {
  17. Return self: MAX_VALUE;
  18. }
  19. }
  20. ?>
  21. # Example 1:
  22. You can access these constants DIRECTLY like so:
  23. * Type the class name exactly.
  24. * Type two (2) colons.
  25. * Type the const name exactly.
  26. # Example 2:
  27. Because our class definition provides two (2) static functions, you can also access them like so:
  28. * Type the class name exactly.
  29. * Type two (2) colons.
  30. * Type the function name exactly (with the parentheses ).

The instance code is as follows:

  1. # Example 1:
  2. $ Min = Constants: MIN_VALUE;
  3. $ Max = Constants: MAX_VALUE;
  4. # Example 2:
  5. $ Min = Constants: getMinValue ();
  6. $ Max = Constants: getMaxValue ();
  7. ?>

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 ).

When class constants are declared and initialized, they cannot be set to other values -- that is why they do not have setMinValue () and setMaxValue () when defining classes () these two methods -- both of them are read-only and static (shared by all objects of this class ).

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.