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__
|
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). |
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 = 'str1'; $str2 = & $str1; // 引用 $str1 = "Changed $str1"; echo $str1." "; echo $str2." "; echo $_SERVER['DOCUMENT_ROOT']." "; // 预定义变量 $gVal = 13; function Test() // 全局变量 { global $gVal; echo $gVal." "; echo $GLOBALS['gVal']." "; } Test(); function test1() { static $a = 0; // 静态变量 echo $a; $a++; } // 可变变量 class foo { var $bar = 'I am bar.'; var $arr = array('I am A.', 'I am B.', 'I am C.'); var $r = 'I am r.'; } $foo = new foo(); $bar = 'bar'; $baz = array('foo', 'bar', 'baz', 'quux'); echo $foo->$bar ." "; echo $foo->$baz[1] ." "; $start = 'b'; $end = 'ar'; echo $foo->{$start . $end} ." "; $arr = 'arr'; echo $foo->$arr[1] ." "; echo $foo->{$arr}[1] ." "; ?>


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

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.

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

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

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

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.

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

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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 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
A free and powerful IDE editor launched by Microsoft

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
Integrate Eclipse with SAP NetWeaver application server.

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.
