Php constant usage in the PHP Getting Started Tutorial

Source: Internet
Author: User
Tags class definition constant min modifier php class scalar

PHP constants
The define () function is used to define constants. Once a constant is defined, it cannot be changed or undefined.

Example of defining constants:

The code is as follows: Copy code

<? Php
Define ("CONSTANT", "Hello! ");
Echo CONSTANT;
?>

Constant names and any other PHP labels follow the same naming rules. A valid constant name starts with a letter or underline followed by any letter, number, or underline.

Constants are case-sensitive by default, and constant identifiers are always capitalized. This value cannot be changed during script execution.

Differences between defining constants and 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 code is as follows: Copy code

If (defined ('myconstant ')){

Echo MYCONSTANT;

 }

(2) determine whether a variable is defined

The code is as follows: Copy code

If (isset ($ myvar )){

Echo "variable $ myvar .";
3}


(3) determine whether a function exists

The code is as follows: Copy code

If (function_exists ('imap _ open ')){
Echo "the imag_open function exists ";
} Else {
Echo "the imag_open function does not exist ";
}


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 code is as follows: Copy code
$ A = 66;
Function t () {echo $ ;}
T (); // at this time, 99 cannot be printed because of the impact of function scope. To print 99, you can change it:
Define ("A", 66 );
Function t () {echo ;}
T ();

2: once a constant is defined, it cannot be redefined. It cannot be cleared or modified;

Constants can also be dynamic.

 

The code is as follows: Copy code

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


 

Object-Oriented const constant modifier

Const.

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 is required. 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 code is as follows: Copy code


<? Php

Class MyClass {

Const CONSTANT = 'constant value'; // use const to declare a CONSTANT and assign it to the initial value.

Function showConstant (){

Echo self: CONSTANT. "<br>"; // use self to access constants. Do not add "$" before constants"

             } 

      } 
Echo MyClass: CONSTANT. "<br>"; // use the class name to access a CONSTANT outside the class, and do not add "$"
$ Class = new MyClass ();

$ Class-> showConstant ();

Echo $ class: CONSTANT; // after PHP 5.3.0

?>

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 code is as follows: Copy code

<? Php

Class MyClass {

Const CONSTANT = 'constant value ';

Function setCONSTANT (){

Self: CONSTANT = 'news constant'; // the program running result will fail.

      } 

                                                                                                                                                                                         

      } 
Echo MyClass: CONSTANT;

                                                                                                                                                                            

?>


CONSTANTS and PHP Class Definitions

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 code is as follows: Copy code

<? Php

Define ('min _ value', '0. 0'); // RIGHT-Works OUTSIDE of a class definition.
Define ('max _ value', '1. 0'); // RIGHT-Works OUTSIDE of a class definition.

// Const MIN_VALUE = 0.0; WRONG-Works INSIDE of a class definition.
// Const MAX_VALUE = 1.0; WRONG-Works INSIDE 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 getMinValue ()
  {
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 ).

The code is as follows: Copy code

<? Php

# Example 1:
$ Min = Constants: 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 ).

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.