search
HomeBackend DevelopmentPHP TutorialPHP Constants and Variables_PHP Tutorial

PHP constants and variables

【Constant】
You can use the define() function to define constants. After PHP 5.3.0, you can use the const keyword to define constants outside the class definition. Once a constant is defined, it cannot be changed or undefined.
Constants can only contain scalar data (boolean, integer, float and string). It is possible to define resource constants, but this should be avoided as it can cause unpredictable results.
The value of a constant can be obtained simply by specifying its name. Unlike variables, constants should not be preceded by the $ sign. If the constant name is dynamic, you can also use the function constant() to get the value of the constant. Use get_defined_constants() to get a list of all defined constants.
If you just want to check whether a certain constant is defined, use the defined() function.
The differences between constants and variables are as follows:
? There is no dollar sign ($) in front of the constant;
? Constants can only be defined using the define() function, not assignment statements;
? Constants can be defined and accessed anywhere regardless of the scope of the variable;
? Once a constant is defined, it cannot be redefined or undefined;
? The value of a constant can only be a scalar value.
Predefined constants

Many constants are defined by different extension libraries and will only appear when these extension libraries are loaded, either dynamically loaded or included at compile time. These special constants are not case-sensitive, as follows:

Name Description
名称 说明
__LINE__ 文件中的当前行号。
__FILE__ 文件的完整路径和文件名。如果用在被包含文件中,则返回被包含的文件名。自 PHP 4.0.2 起,__FILE__ 总是包含一个绝对路径(如果是符号连接,则是解析后的绝对路径),而在此之前的版本有时会包含一个相对路径。
__DIR__ 文件所在的目录。如果用在被包括文件中,则返回被包括的文件所在的目录。它等价于 dirname(__FILE__)。除非是根目录,否则目录中名不包括末尾的斜杠。(PHP 5.3.0中新增) =
__FUNCTION__ 函数名称(PHP 4.3.0 新加)。自 PHP 5 起本常量返回该函数被定义时的名字(区分大小写)。在 PHP 4 中该值总是小写字母的。
__CLASS__ 类的名称(PHP 4.3.0 新加)。自 PHP 5 起本常量返回该类被定义时的名字(区分大小写)。在 PHP 4 中该值总是小写字母的。类名包括其被声明的作用区域(例如 FooBar)。注意自 PHP 5.4 起 __CLASS__ 对 trait 也起作用。当用在 trait 方法中时,__CLASS__ 是调用 trait 方法的类的名字。
__TRAIT__ Trait 的名字(PHP 5.4.0 新加)。自 PHP 5.4 起此常量返回 trait 被定义时的名字(区分大小写)。Trait 名包括其被声明的作用区域(例如 FooBar)。
__METHOD__ 类的方法名(PHP 5.0.0 新加)。返回该方法被定义时的名字(区分大小写)。
__NAMESPACE__ 当前命名空间的名称(区分大小写)。此常量是在编译时定义的(PHP 5.3.0 新增)。
__LINE__
The current line number in the file.
__FILE__ The full path and file name of the file. If used within an included file, returns the name of the included file. As of PHP 4.0.2, __FILE__ always contains an absolute path (or the resolved absolute path in the case of a symbolic link), while versions before that sometimes Contains a relative path.
__DIR__ The directory where the file is located. If used within an included file, returns the directory where the included file is located. It is equivalent to dirname(__FILE__). Directory names do not include the trailing slash unless they are the root directory. (New in PHP 5.3.0) =
__FUNCTION__ Function name (newly added in PHP 4.3.0). Since PHP 5 this constant returns the name of the function as it was defined (case sensitive). In PHP 4 this value is always lowercase.
__CLASS__ The name of the class (new in PHP 4.3.0). Since PHP 5 this constant returns the name of the class when it was defined (case sensitive). In PHP 4 this value is always lowercase. The class name includes the scope in which it is declared (e.g. FooBar). Note that since PHP 5.4 __CLASS__ also works for traits. When used within a trait method, __CLASS__ is the name of the class that calls the trait method.
__TRAIT__ The name of the Trait (new in PHP 5.4.0). Since PHP 5.4 this constant returns the name of the trait as it was defined (case-sensitive). The trait name includes the scope in which it is declared (e.g. FooBar).
__METHOD__ The method name of the class (newly added in PHP 5.0.0). Returns the name of the method as it was defined (case-sensitive).
__NAMESPACE__ The name of the current namespace (case sensitive). This constant is defined at compile time (new in PHP 5.3.0).
【Variable】
Variables in PHP are represented by a dollar sign followed by the variable name. Variable names are case-sensitive. Variable names follow the same rules as other tags in PHP. A valid variable name begins with a letter or an underscore, followed by any number of letters, numbers, or underscores.
Variables are always assigned by value by default. That is, when the value of an expression is assigned to a variable, the value of the entire original expression is assigned to the target variable. This means that, for example, changing the value of one variable while the value of one variable is assigned to another variable will not affect the other variable. PHP also provides another way to assign values ​​to variables: reference assignment. This means that the new variable simply references (in other words, "aliases" or "points to") the original variable. Changing the new variable will affect the original variable and vice versa. To use reference assignment, simply add a & symbol in front of the variable to be assigned (the source variable).
Predefined variables
In PHP 4.2.0 and later versions, the default value of the PHP directive register_globals is off. This is a major change to PHP. Setting register_globals to off affects the global availability of the predefined set of variables. For example, to get the value of DOCUMENT_ROOT, you would have to use $_SERVER['DOCUMENT_ROOT'] instead of $DOCUMENT_ROOT. Another example, use $_GET['id'] instead of $id from the URL http://www.example.com/test Get the id value in .php?id=3, or use $_ENV['HOME'] instead of $HOME to get the value of the environment variable HOME.
?Superglobal variables — Superglobal variables are built-in variables that are always available in all scopes
?$GLOBALS — references all variables available in the global scope
?$_SERVER — Server and execution environment information
?$_GET — HTTP GET variable
?$_POST — HTTP POST variable
?$_FILES — HTTP file upload variable
?$_REQUEST — HTTP Request variable
?$_SESSION — Session variable
?$_ENV — environment variable
?$_COOKIE — HTTP Cookies
?$php_errormsg — Previous error message
?$HTTP_RAW_POST_DATA — Raw POST data
?$http_response_header — HTTP response header
?$argc — Number of arguments passed to the script
?$argv — Array of arguments passed to the script

global keyword
PHP's global variables are a little different from C language. In C language, global variables automatically take effect in functions unless overridden by local variables. This may cause some problems, someone may accidentally change a global variable. Global variables in PHP must be declared as global when used in functions or use a special PHP custom $GLOBALS array. $GLOBALS is an associative array, each variable is an element, the key name corresponds to the variable name, and the value corresponds to the variable's content. $GLOBALS exists in the global scope because $GLOBALS is a superglobal variable.
Static variable
Another important feature of variable scope is static variables.
Mutable variable
Sometimes it is convenient to use mutable variable names. That is to say, the variable name of a variable can be set and used dynamically. An ordinary variable is set by declaration.
To use mutable variables with arrays, an ambiguity must be resolved. This is when writing $$a[1], the parser needs to know whether it wants $a[1] as a variable, or whether it wants $$a as a variable and extracts the variable with index [1] value. The syntax to solve this problem is to use ${$a[1]} for the first case and ${$a}[1] for the second case.

<!--?php
	// 常量,忽略大小写
	define(INVALIDE_VALUE, 12, true);
	echo INVALIDE_VALUE."<br-->";
	echo invalide_value."
";	
	if(defined("INVALIDE_VALUE"))
	{
		echo "INVALIDE_VALUE 已经定义".__LINE__."
";;
	}
	
	// 变量
	$str1 = &#39;str1&#39;;
	$str2 = & $str1;  // 引用	 
	$str1 = "Changed $str1";
	echo $str1."
";
	echo $str2."
";	
	
	echo $_SERVER[&#39;DOCUMENT_ROOT&#39;]."
"; // 预定义变量
	
	$gVal = 13;
	function Test() // 全局变量
	{
		global $gVal;
		echo $gVal."
";
		echo $GLOBALS[&#39;gVal&#39;]."
";
	}
	Test();
	
	function test1()
	{
    	static $a = 0; // 静态变量
    	echo $a;
    	$a++;
	}
	
	// 可变变量
	class foo {
    var $bar = &#39;I am bar.&#39;;
    var $arr = array(&#39;I am A.&#39;, &#39;I am B.&#39;, &#39;I am C.&#39;);
    var $r   = &#39;I am r.&#39;;
	}

	$foo = new foo();
	$bar = &#39;bar&#39;;
	$baz = array(&#39;foo&#39;, &#39;bar&#39;, &#39;baz&#39;, &#39;quux&#39;);
	echo $foo->$bar ."
";
	echo $foo->$baz[1]  ."
";

	$start = &#39;b&#39;;
	$end   = &#39;ar&#39;;
	echo $foo->{$start . $end}  ."
";

	$arr = &#39;arr&#39;;
	echo $foo->$arr[1] ."
";
	echo $foo->{$arr}[1]  ."
";	
?>








www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1022400.htmlTechArticlePHP constants and variables [Constant] You can use the define() function to define constants. After PHP 5.3.0, Constants can be defined outside a class definition using the const keyword. Once a constant is determined...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.