Home > Article > Backend Development > const and global in php
The content shared with you in this article is about const and global in php. It has certain reference value. Friends in need can refer to it
[Explanation]
1. Must be initialized when defined; 2. Not preceded by Add any modifier; 3. Variable name letters are generally capitalized; 4. Constants can be inherited by subclasses;
5. A constant belongs to a class, not to an object
[Function] When some values are fixed, use const
[Distinguish]What is the difference between constants defined by const and constants defined by define()?
Hope that a member variable will not be modified, for example, pi 3.1415926
Definition: const constant name = value; no $ symbol
Access:Class name::Constant name or interface name::Constant name
And:defined('TEXT' );Check whether a constant with a name exists
<?php class A{ const TAX_RATE=0.08; public function payTax($var){ return $var*A::TAX_RATE; } } $a=new A(); echo $a->payTax(200): ?>
Usage 1: const is used for class membersVariables, once defined, cannot be modified,define It is used for global constants , but cannot be used for the definition of class member variables. const can be used in classes, but define cannot.
Usage 2: Constants defined by const are case-sensitive, and define can specify whether case-sensitivity is achieved through the third parameter (TRUE indicating case-insensitivity). Define a constant at runtime. define('TXE',100,TRUE);
Usage three: const cannot define constants in conditional statements, but the define function can. if($a>10){define('LE','hello');}
【Citation: http://www.phptd.com/?action-viewnews-itemid-6147】
1. Super global variable $GLOBALS
There are many super global variables in PHP. The following are all superglobal variables (Superglobal):
$GLOBALS, $_SERVER, $ _GET, $_POST, $_FILES, $_COOKIE, $_SESSION, $_REQUEST, $_ENV.
Official description:
$GLOBALS — refers to all variables available in the global scope.
A global combined array containing all variables. The name of the variable is the key of the array.
The global variables that have appeared can be obtained through the $GLOBALS array.
In the PHP life cycle, the so-called global variables defined outside the function body cannot be directly obtained inside the function.
$foo = "Example content"; test();function test() { $foo = "local variable"; echo '$foo in current scope: ' . $foo . "<br>"; echo '$foo in global scope: ' . $GLOBALS["foo"] . "<br>"; }In the above example, to access external $foo, you must use the $GLOBALS array. This also applies to external global variables that come in through include files.
Global in php also has such a function. The difference between it and $GLOBALS is:
2. Example explanation
5
Why not 2 5s but 1 0 and What about 1 5?
Modify the example again:
The above is the detailed content of const and global in php. For more information, please follow other related articles on the PHP Chinese website!