Home >Backend Development >PHP Tutorial >The use of custom constants and system constants in ThinkPHP_PHP tutorial
We all know that a constant is to define an unchanging quantity. The definition rule of a constant in PHP is define("constant name", "constant value");
That is, you can use this constant in all pages. Simply defining a few constants does not make any sense. The important thing is to use the constant area to optimize the code. What I mean by optimizing the code is to improve the maintainability of the code. Sometimes it also plays a role in simplifying the code, but this is definitely not the main purpose.
In traditional code writing, we use direct writing, such as URL addresses, etc. Although these things can be directly used to implement functions, in the later maintenance process of the program, they must first be It is very difficult. Although it is possible to use the replacement function, it is not a long-term solution, and there is a better way than this, which is to define constants for use. In this way, in the later maintenance, if the drive letter or variable is changed Information, just modify the variables directly. Although the reason is very simple, it is not easy to use it flexibly.
In addition to custom constants, there are also some system constants. If you want to see these constant information, you can use the following code to achieve it:
// echo "
";<br> // var_dump(get_defined_constants());<br> // echo "";
You will be stuck with a large list of things, which contain all the system constants for you to use, but one thing to note is that whether it is our customized constants or system constants, the more commonly used ones are in the latter one. Things to note:
The following is an example code of how I define constants, taking the think template as an example
//定义网站域名常量 define("SET_URL","http://shop.com/"); //定义前台HOME模块的css,img。js的常量信息 define("CSS_URL",SET_URL."Public/Home/css/"); define("IMG_URL",SET_URL."Public/Home/img/"); define("JS_URL",SET_URL."Public/Home/js/"); //定义后台Admin模块的css,img。js的常量信息 define("ADMIN_CSS_URL",SET_URL."Public/Admin/css/"); define("ADMIN_IMG_URL",SET_URL."Public/Admin/img/"); define("ADMIN_JS_URL",SET_URL."Public/Admin/js/");