Home > Article > Backend Development > Detailed explanation of the definition, usage, and difference examples of constants and variables in PHP
phpConstants and variablesDetailed explanation of examples
[PHP receives parameters under the command line]
If debugging php on the command line, the parameters passed in are obtained through $argv. Note that it contains the file name element, and the number of elements in the array is obtained through $argc.
means that the name of the variable is variable, and the identifier of the variable can be value of another variable.
For example: the second statement assigns a value to the variable argv1.
<?php $varName = 'argv1'; $$varName = 'value1'; var_dump($argv1); ?>
[Constant]
Use define to define, cannot be deleted or modified, write the name directly when calling. define also has a three-parameter version. The third parameter represents whether it is case-insensitive. The default is false.
<?php define('pi',3.14); echo pi; ?>
Tips: First check whether the constant has been defined before defining it, use the defined function:
<?php if(!defined('pi')) define('pi',3.14); else echo 'pi has been defined<br>'; ?>
For constants with special symbols, you need to use the constant function to call them. Note that the constant name should be Add quotation marks, for example:
<?php if(!defined('= =')) define('= =','puzzled'); else echo 'pi has been defined<br>'; echo constant('= ='); ?>
Get all defined constants:
<?php var_dump(get_defined_constants()); ?>
[Magic variable]
LINE Get the current location OK, FILE gets the current path.
An application:
Use the str_replace function to replace the file name in the file with the path + file name to ensure that the file path changes can still be accessed.
str_replace(4aa413e8cde63fcbc126f17ea466f577,c5d99ca4839f35b092c01bbffd8ca103,25d611ff51593c69b3496a1acd4c3130,e890a51a8b8396b279129fe6a74f5bfd);
<?php define('ROOT',str_replace('a.php','',FILE)); echo ROOT; ?>
【Base】
Add 0 before the number to represent octal, and add 0x to represent hexadecimal.
[String type]
Both double quotes and single quotes can be used, but double quotes can parse internal variables, but single quotes are more efficient .
Double quotes parse variables: { } can ensure that variable name is separated from other parts.
<?php $name = "test"; echo "username is {$name}"; ?>
The above is the detailed content of Detailed explanation of the definition, usage, and difference examples of constants and variables in PHP. For more information, please follow other related articles on the PHP Chinese website!