PHP Chinese Manual 2,_PHP Tutorial
Jul 13, 2016 am 09:44 AMPHP Chinese Manual 2,
<code><code> 11. Exception handling <code><code>Users can extend PHP’s built-in exception handling classes with custom exception handling classes. The following code illustrates which properties and methods in the built-in exception handling class are accessible and inheritable in subclasses. Translator's Note: The following code is only to illustrate the structure of the built-in exception handling class. It is not a usable code with practical significance.
<code>class Exception{protected $message = 'Unknown exception'; //Exception information
protected $code = 0; //User-defined exception code
protected $file; //The file name where the exception occurred
protected $line; //The code line number where the exception occurred
function __construct($message = null, $code = 0);
final function getMessage(); // Return exception information
final function getCode(); // Return exception code
final function getFile(); // Return the file name where the exception occurred
final function getLine(); // Returns the code line number where the exception occurred
final function getTrace(); // backtrace() array
final function getTraceAsString(); // getTrace formatted into a string () Information
/* Overloadable method*/
function __toString(); // Outputable string
}
?><code>class Exception{
protected $message = 'Unknown exception'; // 異常信息
protected $code = 0; // 用戶自定義異常代碼
protected $file; // 發(fā)生異常的文件名
protected $line; // 發(fā)生異常的代碼行號(hào)
function __construct($message = null, $code = 0);
final function getMessage(); // 返回異常信息
final function getCode(); // 返回異常代碼
final function getFile(); // 返回發(fā)生異常的文件名
final function getLine(); // 返回發(fā)生異常的代碼行號(hào)
final function getTrace(); // backtrace() 數(shù)組
final function getTraceAsString(); // 已格成化成字符串的 getTrace() 信息
/* 可重載的方法 */
function __toString(); // 可輸出的字符串
}
?>
If you use a custom class to extend the built-in exception handling class and redefine the constructor, it is recommended to call parent::__construct() at the same time to check whether all variables have been assigned values. When the object wants to output a string, you can overload __toString() and customize the output style.
Extend PHP’s built-in exception handling class
<code><?php<br />// 自定義一個(gè)異常處理類<br />class MyException extends Exception{ // 重定義構(gòu)造器使 message 變?yōu)楸仨毐恢付ǖ膶傩?lt;br /> public function __construct($message, $code = 0) {<br /> // 自定義的代碼 // 確保所有變量都被正確賦值<br /> parent::__construct($message, $code);<br />}<br />// 自定義字符串輸出的樣式<br />public function __toString() {<br /> return __CLASS__ . ": [{$this->code}]:?{$this->message}n";<br>}<br>public function?customFunction() {<br>? ? echo?"A Custom function for this type of exceptionn";<br>? ? }<br>}<br><span>//</span>創(chuàng)建一個(gè)用于測(cè)試異常處理機(jī)制的類<br>class?TestException{<br>public?$var;<br>const?THROW_NONE?=?0;<br>const?THROW_CUSTOM?=?1;<br>const?THROW_DEFAULT?=?2;<br>function?__construct($avalue?=?self::THROW_NONE) {<br>switch ($avalue) {<br>case?self::THROW_CUSTOM:<br>// 拋出自定義異常<br>throw new?MyException('1 is an invalid parameter',?5);<br>break;<br>case?self::THROW_DEFAULT:<br>// 拋出默認(rèn)的異常<br>throw new?Exception('2 isnt allowed as a parameter',?6);<br>break;<br>default:<br>// 沒有異常的情況下,創(chuàng)建一個(gè)對(duì)象<br>$this->var?=?$avalue;<br>break;<br>}<br>}<br>}<br>// 例子 1<br>try {<br>$o?= new?TestException(TestException::THROW_CUSTOM);<br>} catch (MyException $e) {?// 捕獲異常<br>echo?"Caught my exceptionn",?$e;<br>$e->customFunction();<br>} catch (Exception $e) {?// 被忽略<br>echo?"Caught Default Exceptionn",?$e;<br>}<br>// 執(zhí)行后續(xù)代碼<br>var_dump($o);<br>echo?"nn";<br>// 例子 2<br>try {<br>$o?= new?TestException(TestException::THROW_DEFAULT);<br>} catch (MyException $e) {?// 不能匹配異常的種類,被忽略<br>echo?"Caught my exceptionn",?$e;<br>$e->customFunction();<br>} catch (Exception $e) {?// 捕獲異常<br>echo?"Caught Default Exceptionn",?$e;<br>}<br>// 執(zhí)行后續(xù)代碼<br>var_dump($o);<br>echo?"nn";<br>// 例子 3<br>try {<br>$o?= new?TestException(TestException::THROW_CUSTOM);<br>} catch (Exception $e) {?// 捕獲異常<br>echo?"Default Exception caughtn",?$e;<br>}<br>// 執(zhí)行后續(xù)代碼<br>var_dump($o);<br>echo?"nn";<br>// 例子 4<br>try {<br>$o?= new?TestException();<br>} catch (Exception $e) {?// 沒有異常,被忽略<br>echo?"Default Exception caughtn",?$e;<br>}<br>// 執(zhí)行后續(xù)代碼<br>var_dump($o);<br>echo?"nn";<br>?> 12. Generator <code><code>Generators allow you to write code in a foreach block to iterate over a set of data without creating an array in memory, which would hit your memory limit or take up considerable processing time. Instead, you can write a generator function, just like a normal custom function, and instead of a normal function returning only once, the generator can yield as many times as needed in order to generate values ??that need to be iterated over.
<code><?php<br />function xrange($start, $limit, $step = 1) {<br /> if ($start < $limit) {<br /> if ($step <= 0) {<br /> throw new LogicException('Step must be ve');<br />}<br /> for ($i = $start; $i <= $limit; $i = $step) {<br /> yield $i;<br /> }<br /> } else {<br /> if ($step >=?0) {<br>? ? ? ? ? ? throw new?LogicException('Step must be -ve');<br>? ? ? ? }<br>? ? ? ? for ($i?=?$start;?$i?>=?$limit;?$i? =?$step) {<br>? ? ? ? ? ? yield?$i;<br>? ? ? ? }<br>? ? }<br>}<br>/* Note that both range() and xrange() result in the same<br>* output below. */<br>echo?'Single digit odd numbers from range(): ';<br>foreach (range(1,?9,?2) as?$number) {<br>? ? echo?"$number?";<br>}<br>echo?"n";<br>echo?'Single digit odd numbers from xrange(): ';<br>foreach (xrange(1,?9,?2) as?$number) {<br>? ? echo?"$number?";<br>}<br>?>Single digit odd numbers from range(): 1 3 5 7 9 Single digit odd numbers from xrange(): 1 3 5 7 9
Comparing generators with?Iterator?objects
The primary advantage of generators is their simplicity. Much less boilerplate code has to be written compared to implementing anIterator?class, and the code is generally much more readable. For example, the following function and class are equivalent:
<code><?php<br />function getLinesFromFile($fileName) {<br /> if (!$fileHandle = fopen($fileName, 'r')) {<br /> return;<br />}<br />while (false !== $line = fgets($fileHandle)) {<br /> yield $line;<br />}<br />fclose($fileHandle);<br />}<br />// versus...<br />class LineIterator implements Iterator {<br /> protected $fileHandle;<br /> protected $line;<br /> protected $i;<br /> public function __construct($fileName) {<br /> if (!$this->fileHandle = fopen($fileName, 'r')) {<br /> throw new RuntimeException('Couldn't open file "' . $fileName . '"');<br /> }<br /> }<br /> public function rewind() {<br /> fseek($this->fileHandle, 0);<br /> $this->line = fgets($this->fileHandle);<br /> $this->i = 0;<br /> }<br /> public function valid() {<br /> return false !== $this->line;<br /> }<br /> public function current() {<br /> return $this->line;<br /> }<br /> public function key() {<br /> return $this->i;<br /> }<br /> public function next() {<br /> if (false !== $this->line) {<br /> $this->line = fgets($this->fileHandle);<br /> $this->i ;<br /> }<br /> }<br /> public function __destruct() {<br /> fclose($this->fileHandle);<br /> }<br /> }<br />?> 13. Quote <code><code> <code>$a =& $b; //This means <code>$a =& $b; //這意味著 $a 和 $b 指向了同一個(gè)變量。$a 和 $b 在這里是完全相同的,這并不是 $a 指向了 $b 或者· //相反,而是 $a 和 $b 指向了同一個(gè)地方。?><code>$a
and
$bpoints to the same variable.
$aand
$bare exactly the same here, which is not the case with
$apoints to
$bor·???????????????????????????????????????????????????????????????? // Instead, it is ???????????
$aand?
$b points to the same place.
?>
<code>
If an array with a reference is copied, its value will not be dereferenced. The same is true for passing array values ??to functions. If an undefined variable is assigned by reference, passed by reference, or returned by reference, the variable is automatically created.
function foo(&$var) { }
foo($a); // $a is "created" and assigned to null
$b = array();<code>$bar =& new fooclass();$foo =& find_var($bar);
?>
foo($b['b']); var_dump(array_key_exists('b', $b)); // bool(true)
?>$c = new StdClass;?>?> ?>?>foo($c->d);?>?> ?>?>var_dump(property_exists($c, 'd')); // bool(true)?>?> ?>?>?>?>?> ?>?>The same syntax can be used in functions, which return references, and in the ?>new?> operator (PHP 4.0.4 and later): ?>?> <code>?>$bar =& new fooclass();$foo =& find_var($bar);
?>?>?> ?>?>If a reference is assigned to a variable declared as ?>global?> inside a function, the reference is only visible inside the function. This can be avoided by using the ?>?>$GLOBALS?>?> array. Reference global variables within a function: ?>?><code>$var1 = "Example variable";
$var2 = "";
function global_references($use_globals){
global $var1, $var2;
if (!$use_globals) {
$var2 =& $var1; // visible only inside the function
} else {
$GLOBALS["var2"] =& $var1; // visible also in global context
}
}
global_references(false);
echo "var2 is set to '$var2'n"; // var2 is set to ''
global_references(true);
echo "var2 is set to '$var2'n"; // var2 is set to 'Example variable'
?> Think of global $var; as the abbreviation of $var =& $GLOBALS['var']; . Thus assigning other references to $var only changes the reference of the local variable.
If a variable with a reference is assigned a value in a foreach statement, the referenced object is also changed.
$ref = 0;
$row =& $ref;
foreach (array(1, 2, 3) as $row) {// do something}
echo $ref; // 3 - last element of the iterated array
?>
The second thing a reference does is pass a variable by reference. This is accomplished by creating a local variable within the function and that variable references the same content in the calling scope. For example:
<code><code>function foo(&$var){$var ;
}
$a=5;
foo($a);
?>function foo(&$var){
$var ;
}
$a=5;
foo($ a);
?> will make $a become 6. This is because the variable $var in the foo function points to and $a points to the same content. See Passing by Reference for a more detailed explanation. The third thing a reference does is reference return. References are not pointers.
You can pass a variable by reference to a function so that the function can modify the value of its argument.
<code><span><?php<br />function foo(&$var){<br />$var ;<br />}<br />$a=5;<br />foo($a);// $a is 6 here<br />?></span> <code><span><?php<br />function foo(&$var){<br />$var ;<br />}<br />$a=5;<br />foo($ a);// $a is 6 here<br />?></span>Note that there are no reference symbols in function calls - only in function definitions. The function definition alone is enough for parameters to be passed correctly by reference
The following can be passed by reference:Variables, such as foo($a); New statements, such as foo(new foobar());
References returned from functionsAny other expression cannot be passed by reference, and the result is undefined. <code><span><?php<br />function bar(){ // Note the missing &<br />$a = 5;<br />return $a;<br />}<br />foo(bar()); // 自 PHP 5.0.5 起導(dǎo)致致命錯(cuò)誤<br />foo($a = 5) // 表達(dá)式,不是變量<br />foo(5) // 導(dǎo)致致命錯(cuò)誤<br />?></span>
<code><span><?php<br />function bar(){ // Note the missing &<br />$a = 5;<br />return $a;<br />}<br / >foo(bar()); // Causes fatal error since PHP 5.0.5<br />foo($a = 5) // Expression, not variable<br />foo(5) // Causes fatal error <br />?><em> Reference return is used when you want to use a function to find which variable the reference should be bound to.
Don't ?> use return references to increase performance, the engine is smart enough to optimize it itself. Only return references if there is a valid technical reason! To return a reference, use this syntax: ?>?><code><span><?php<br />class foo {<br /> public $value = 42;<br /> public function &getValue() {<br /> return $this->value;<br /> }<br />}<br />$obj = new foo;<br />$myValue = &$obj->getValue(); // $myValue is a reference to $obj->value, which is 42.<br />$obj->value = 2;<br />echo $myValue; // prints the new value of $obj->value, i.e. 2.<br />?></span> In this example, the properties of the object returned by the getValue function will be assigned values ??instead of copied, just like no reference syntax is used. Unlike parameter passing, the ampersand must be used in both places here - indicating that a reference is returned, not a usual copy, and also indicating that $myValue is bound as a reference, not a usual assignment. When you unset a reference, you just break the binding between the variable name and the variable's contents. This does not mean that the variable contents are destroyed. <code><code>$a = 1;$b =& $a;
unset($a);
?>$a = 1;
$b =& $a;
unset($a);
?> will not unset $b, just $a. Reference positioning: global reference: When declaring a variable with global $var a reference to the global variable is actually established. That is the same as doing this: <code><span><?php<br />$var =& $GLOBALS["var"]; //這意味著,例如,unset <var><var>$var</var></var> 不會(huì) unset 全局變量。<br />?></span> <code><span><?php<br />$var =& $GLOBALS["var"]; //This means, for example, that unset <var><var>$var</var></var> does not Will unset global variables. <br />?></span>
$this: In a method of an object, $this is always a reference to the object that calls it.
14. Predefined variables
Superglobal variables — Superglobal variables are built-in variables that are always available in all scopes. Many predefined variables in PHP are "superglobal", which means that they are in all scopes of a script. Available in all. They can be accessed within a function or method without executingglobal $variable; . These superglobal variables are:
$GLOBALS;$_SERVER;$_GET;$_POST;$_FILES;$_COOKIE;$_SESSION;$_REQUEST;$_ENV
By default, all superglobal variables are available. However, there are some directives that affect this availability. <code><span><?php<br />function test() {<br />$foo = "local variable";<br />echo '$foo in global scope: ' . $GLOBALS["foo"] . "n";//$foo in global scope: Example content<br />echo '$foo in current scope: ' . $foo . "n";//$foo in current scope: local variable<br />}<br />$foo = "Example content";<br />test();<br />?></span>$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. <code><var><?php<br />function test() {<br />$foo = "local variable";<br />echo '$foo in global scope: ' . $GLOBALS["foo "] . "n";//$foo in global scope: Example content<br />echo '$foo in current scope: ' . $foo . "n";//$foo in current scope: local variable<br />}<br />$foo = "Example content";<br />test();<br />?></var> "Superglobal" is also called the global variable of automation. This means that it is available in all scopes of the script. There is no need to use
global $variable;in a function or method to access it. Unlike all other superglobal variables, $GLOBALS is always available in PHP.
$_SERVER
is an array containing information such as header, path, and script locations. The items in this array are represented by
Web server creation. You may or may not be able to find the following elements in $_SERVER. List:
'PHP_SELF': The file name of the currently executing script, related to the document root. For example, use in a script at http://example.com/test.php/foo.bar
$_SERVER['PHP_SELF'] will get /test.php/foo.bar.
'SERVER_ADDR': The IP address of the server where the script is currently running.
'SERVER_NAME': The host name of the server where the script is currently running. If the script is running on a virtual host, the name is determined by the value set for that virtual host.
'SERVER_PROTOCOL': The name and version of the communication protocol when requesting the page. For example, "HTTP/1.0".
?>'REQUEST_METHOD': The request method used to access the page; for example, "GET", "HEAD", "POST", "PUT". ?>?> ?>?>'REQUEST_TIME': The timestamp when the request started. Available since PHP 5.1.0. ?>?>'QUERY_STRING': query string (query string), if any, through which page access is performed.
'HTTP_HOST': The content of the Host: item in the current request header, if it exists.
'HTTP_REFERER': Directs the user agent to the address of the previous page of the current page (if one exists). Determined by user agent settings. Not all user agents will set this item, and some also provide the function of modifying HTTP_REFERER. In short, the value is not trustworthy.
'HTTP_USER_AGENT': The content of the User-Agent: item in the current request header, if it exists. This string indicates information about the user agent accessing this page.
'REMOTE_ADDR': The IP address of the user browsing the current page.
'REMOTE_HOST': The host name of the user browsing the current page. DNS reverse resolution does not depend on the user's REMOTE_ADDR.
'SERVER_PORT': The port used by the web server. The default value is "80". If using SSL secure connection, this value is the HTTP port set by the user.
$_GET: Array of variables passed to the current script via URL parameters. GET is passed via urldecode().
$_POST: Array of variables passed to the current script via the HTTP POST method.
$_FILES: An array of items uploaded to the current script via HTTP POST.
$_REQUEST — HTTP Request variable, when run in command line mode, will not contain argv and argc information; they will exist in $_SERVERArray.
Since the variables in $_REQUEST are passed to the script file through the GET, POST and COOKIE input mechanisms, they can be tampered with by remote users and are not trustworthy. The items of this array and their order depend on the configuration of PHP's variables_order directive.
$_SESSION: An array of SESSION variables available in the current script.
move_uploaded_file() - Move the uploaded file to a new location; import_request_variables() - Import GET/POST/Cookie variables into the global scope; session_start() - Start a new session or reuse an existing session; getenv() - Get the value of an environment variable;$_ENV: An array of variables passed to the current script through the environment. These variables are imported from the PHP parser's runtime environment into PHP's global namespace. Many are provided by shells that support PHP running, and different systems are likely to run different kinds of shells, so a definitive list is impossible. Check your shell documentation for a list of defined environment variables. Other environment variables include CGI variables, regardless of whether PHP is running as a server module or a CGI processor.
$_COOKIE: Array of variables passed to the current script through HTTP Cookies. setcookie() - Send a cookie
$php_errormsg — Previous error message; $php_errormsg variable contains the latest error message generated by PHP. This variable is only available in the scope where the error occurred, and requires the track_errors configuration item to be turned on (the default is turned off). If the user defines an error handler (set_error_handler()) and returns <code>FALSE, $php_errormsg will be set.
<code><code>@strpos();echo $php_errormsg; //Wrong parameter count for strpos()
?>@strpos();
echo $php_errormsg; //Wrong parameter count for strpos()
?>
$HTTP_RAW_POST_DATA — Raw POST data. $HTTP_RAW_POST_DATA Contains the raw data submitted by POST. See always_populate_raw_post_data In general, use php://input instead of $HTTP_RAW_POST_DATA.
$http_response_header — HTTP response header: $http_response_headerThe array is similar to the get_headers() function. When using an HTTP wrapper, $http_response_header will be populated with HTTP response headers. $http_response_header will be created in the local scope.
?> <code><span><?php<br />function get_contents() {<br /> file_get_contents("http://example.com");<br /> var_dump($http_response_header);<br />}<br />get_contents();<br />var_dump($http_response_header);<br />?></span>$argc — 傳遞給腳本的參數(shù)數(shù)目:包含當(dāng)運(yùn)行于命令行下時(shí)傳遞給當(dāng)前腳本的參數(shù)的數(shù)目。腳本的文件名總是作為參數(shù)傳遞給當(dāng)前腳本,因此 $argc 的最小值為 1。這個(gè)變量?jī)H在 register_argc_argv 打開時(shí)可用。
$argv — 傳遞給腳本的參數(shù)數(shù)組:包含當(dāng)運(yùn)行于命令行下時(shí)傳遞給當(dāng)前腳本的參數(shù)的數(shù)組。第一個(gè)參數(shù)總是當(dāng)前腳本的文件名,因此 $argv[0] 就是腳本文件名。這個(gè)變量?jī)H在 register_argc_argv 打開時(shí)可用。
- getopt() - 從命令行參數(shù)列表中獲取選項(xiàng)
Exception是所有異常的基類。類摘要:
Exception { /* 屬性 */ protectedstring$message ; protectedint$code ; protectedstring$file ; protectedint$line ; /* 方法 */ public__construct ([ string<code>$message = "" [, int<code>$code = 0 [, Exception<code>$previous = <code>NULL ]]] ) finalpublicstringgetMessage ( void ) finalpublicExceptiongetPrevious ( void ) finalpublicintgetCode ( void ) finalpublicstringgetFile ( void ) finalpublicintgetLine ( void ) finalpublicarraygetTrace ( void ) finalpublicstringgetTraceAsString ( void ) publicstring__toString ( void ) finalprivatevoid__clone ( void ) } 屬性:message:異常消息內(nèi)容;code:異常代碼;file:拋出異常的文件名;line:拋出異常在該文件中的行號(hào)Exception::__construct — 異常構(gòu)造函數(shù)
參數(shù):message:拋出的異常消息內(nèi)容。code:異常代碼。previous:異常鏈中的前一個(gè)異常。Exception::getMessage — 獲取異常消息內(nèi)容
參數(shù):此函數(shù)沒有參數(shù)。Exception::getPrevious — 返回異常鏈中的前一個(gè)異常
參數(shù):Exception::getPrevious — 返回異常鏈中的前一個(gè)異常。追蹤異常,并循環(huán)打印。 <code><span><?php<br />class MyCustomException extends Exception {}<br />function doStuff() {<br /> try {<br /> throw new InvalidArgumentException("You are doing it wrong!", 112);<br /> } catch(Exception $e) {<br /> throw new MyCustomException("Something happend", 911, $e);<br /> }<br />}<br />try {<br /> doStuff();<br /> } catch(Exception $e) {<br /> do {<br /> printf("%s:%d %s (%d) [%s]\n", $e->getFile(), $e->getLine(), $e->getMessage(), $e- >getCode(), get_class($e));<br /> } while($e = $e->getPrevious());<br /> }<br />?></span>以上例程的輸出類似于:
<span>/home/bjori/ex.php:8 Something happend (911) [MyCustomException] /home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentException] </span>
Exception::getCode — 獲取異常代碼
參數(shù):此函數(shù)沒有參數(shù)。Exception::getFile — 獲取發(fā)生異常的程序文件名稱
參數(shù):此函數(shù)沒有參數(shù)。Exception::getLine — 獲取發(fā)生異常的代碼在文件中的行號(hào)
Parameters: This function has no parameters.Exception::getTrace — Get exception tracing information
Parameters: This function has no parameters.Exception::getTraceAsString — Get exception tracing information of string type
Parameters: This function has no parameters.Exception::__toString — Convert exception object to string
Parameters: This function has no parameters.Exception::__clone — Exception clone
Parameters: This function has no parameters. There is no return value, and exceptions are not allowed to be cloned.ErrorException::__construct — Exception constructor
Parameters: message: The thrown exception message content. code: exception code. severity: The severity level of the exception. filename: The file name where the exception was thrown. lineno: The line number where the exception was thrown. previous: The previous exception in the exception chain.ErrorException::getSeverity — Get the severity of the exception
Parameters: This function has no parameters. <code><code>try {throw new ErrorException("Exception message", 0, 75);
} catch(ErrorException $e) {
echo "This exception severity is: " . $e->getSeverity();
}
?>try {
throw new ErrorException("Exception message", 0, 75);
} catch(ErrorException $e) {
echo "This exception severity is: " . $e->getSeverity();
}
?> 16. Predefined interface Traversable interface:
An interface to detect whether a class can be traversed using foreach. A basic abstract interface that cannot be implemented alone. Instead it must be implemented by the IteratorAggregate or Iterator interface. Built-in classes that implement this interface can use foreach for iteration without implementing the IteratorAggregate or Iterator interface. This is an internal engine interface that cannot be implemented in PHP scripts. The IteratorAggregate or Iterator interface can be used instead.
Traversable { } This interface does not have any methods. Its function is only as the basic interface for all traversable classes. Iterator interface:An interface that can iterate internally via its own external iterator or class.
IteratorextendsTraversable { /* Method */ abstractpublicmixedcurrent (void) abstractpublicscalarkey (void) abstractpublicvoidnext (void) abstractpublicvoidrewind (void) abstractpublicbooleanvalid (void) }Iterator::current — Returns the current element: no parameters, any type can be returned.
Iterator::key — Returns the key of the current element: no parameters, returns a scalar on success, returns null on failure.
Iterator::next — Move forward to the next element: no parameters, any returns will be ignored. This method is called after the foreach loop .
Iterator::rewind — Returns the first element of the iterator: this is the first method called when starting a foreach loop. It will not be called after the foreach loop . Without parameters, any returns will be ignored.
Iterator::valid — Check whether the current position is valid: This method is called after the Iterator::rewind() and Iterator::next() methods to check whether the current position is valid. Without parameters, the return will be converted to boolean. Returns <code>TRUE on success, or <code>FALSE on failure.
IteratorAggregate::getIterator — Gets an external iterator: no parameters, an instance of a class that implements the Iterator or Traversable interface.
ArrayAccess (array access) interface:An interface that provides the ability to access objects like arrays.
?> ArrayAccess { /* 方法 */ abstractpublicbooleanoffsetExists ( mixed<code>$offset ) abstractpublicmixedoffsetGet ( mixed<code>$offset ) abstractpublicvoidoffsetSet ( mixed<code>$offset , mixed<code>$value ) abstractpublicvoidoffsetUnset ( mixed<code>$offset ) }ArrayAccess::offsetExists — 檢查一個(gè)偏移位置是否存在:對(duì)一個(gè)實(shí)現(xiàn)了 ArrayAccess 接口的對(duì)象使用 isset() 或 empty() 時(shí),此方法將執(zhí)行。當(dāng)使用 empty() 并且僅當(dāng) ArrayAccess::offsetExists() 返回 <code>TRUE 時(shí),ArrayAccess::offsetGet() 將被調(diào)用以檢查是為否空。參數(shù):offset 需要檢查的偏移位置。成功時(shí)返回 <code>TRUE, 或者在失敗時(shí)返回 <code>FALSE。如果一個(gè)非布爾型返回值被返回,將被轉(zhuǎn)換為布爾型。
<code><span><?php<br />class obj implements arrayaccess {<br /> public function offsetSet($offset, $value) {<br /> var_dump(__METHOD__);<br />}<br />public function offsetExists($var) {<br /> var_dump(__METHOD__);<br /> if ($var == "foobar") {<br /> return true;<br /> }<br /> return false;<br />}<br />public function offsetUnset($var) {<br /> var_dump(__METHOD__);<br /> }<br />public function offsetGet($var) {<br /> var_dump(__METHOD__);<br /> return "value";<br /> }<br />}<br />$obj = new obj;<br />echo "Runs obj::offsetExists()\n";<br />var_dump(isset($obj["foobar"]));<br />echo "\nRuns obj::offsetExists() and obj::offsetGet()\n";<br />var_dump(empty($obj["foobar"]));<br />echo "\nRuns obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get\n";<br />var_dump(empty($obj["foobaz"]));<br />?></span>以上例程的輸出類似于:
<span>Runs obj::offsetExists() string(17) "obj::offsetExists" bool(true) Runs obj::offsetExists() and obj::offsetGet() string(17) "obj::offsetExists" string(14) "obj::offsetGet" bool(false) Runs obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get string(17) "obj::offsetExists" bool(true) </span>
ArrayAccess::offsetGet?—?獲取一個(gè)偏移位置的值:當(dāng)檢查一個(gè)偏移位置是否為?empty()?時(shí),此方法被執(zhí)行。
參數(shù):offset 需要獲取的偏移位置。返回值:可返回任何類型。ArrayAccess::offsetSet?—?設(shè)置一個(gè)偏移位置的值:參數(shù):offset?待設(shè)置的偏移位置。value?需要設(shè)置的值。沒有返回值。
如果另一個(gè)值不可用,那么?<code>offset?參數(shù)將被設(shè)置為?<code>NULL。
?
ArrayAccess::offsetUnset?—?復(fù)位一個(gè)偏移位置的值:當(dāng)使用?(unset)?進(jìn)行類型轉(zhuǎn)換時(shí),該方法不會(huì)被調(diào)用。
<code>參數(shù):offset?待復(fù)位的偏移位置。沒有返回值。?
序列化接口:
?
Serializable::serialize?—?對(duì)象的字符串表示。這個(gè)方法擔(dān)當(dāng)著對(duì)象析構(gòu)器的角色。在此方法之后,__destruct()?方法將不會(huì)被調(diào)用。此函數(shù)沒有參數(shù),返回值:返回對(duì)象的字符串表示或者?<code>NULL?。
Serializable::unserialize?—?構(gòu)造對(duì)象。這個(gè)方法擔(dān)當(dāng)著對(duì)象構(gòu)造器的角色。在此方法之后,__construct()?將不會(huì)被調(diào)用。參數(shù):serialized?對(duì)象的字符串表示。
Closure::__construct?—?用于禁止實(shí)例化的構(gòu)造函數(shù)。這個(gè)方法僅用于禁止實(shí)例化一個(gè)?Closure?類的對(duì)象。這個(gè)類的對(duì)象的創(chuàng)建方法寫在?匿名函數(shù)?頁。此函數(shù)沒有參數(shù),沒有返回值。
Closure::bind?—?復(fù)制一個(gè)閉包,綁定指定的$this對(duì)象和類作用域。這個(gè)方法是?Closure::bindTo()?的靜態(tài)版本。
?
?
Parameter: closure Anonymous function that needs to be bound. newthis requires an object bound to an anonymous function, or <code>NULL creates an unbound closure. newscope is the class scope you want to bind to the closure, or 'static' means unchanged. If an object is passed in, the type name of the object is used. Class scope is used to determine the visibility of private, protected methods of the $this object within the closure. Returns a new Closure object or <code>FALSE on failure
<code><code>class A {
private static $sfoo = 1;
private $ifoo = 2;
}
$cl1 = static function() {
return A::$sfoo;
};
$cl2 = function() {
return $this->ifoo;
};
$bcl1?=?Closure::bind($cl1,?null,?'A');
$bcl2?=?Closure::bind($cl2, new?A(),?'A');
echo?$bcl1(),?"n"; ? ?//1
echo?$bcl2(),?"n"; ? ?//2
?>class A {
private static $sfoo = 1;
private $ifoo = 2;
}
$cl1 = static function() {
return A::$sfoo;
};
$cl2 = function() {
return $this->ifoo;
} ;
$bcl1 = Closure::bind($cl1, null, 'A');
$bcl2 = Closure::bind($cl2, new A(), 'A');
/>echo $bcl1(), "n"; //1
echo $bcl2(), "n"; //2
?> Closure::bindTo — Copies the current closure object and binds the specified $this object and class scope. Create and return an anonymous function, which has the same function body as the current object and binds the same variables, but can bind different objects or a new class scope. The "bound object" determines the value of $this<code>newscope in the function body, and the "class scope" represents a type and determines which private and protected methods can be called in this anonymous function. In other words, the methods that $this can call at this time are the same as the member functions of the <code>newthis class. Static closures cannot have bound objects (the value of the parameter should be set to <code>NULL) but their class scope can still be changed using the bubdTo method. If you just want to copy an anonymous function, you can use cloning instead. Parameter: newthis is an object bound to the anonymous function, or <code>NULL to unbind. newscope associates to the class scope of the anonymous function, or 'static' maintains the current state. If it is an object, the type of this object is used in the scope of the experience class. This determines the visibility of protected, private member methods of the bound object. Return value: Returns the newly created Closure object or returns <code>FALSE
on failure
<code><span><?php<br />class A {<br /> function __construct($val) {<br /> $this->val?=?$val;<br>? ? }<br>? ? function?getClosure() {<br>? ? ? ? //returns closure bound to this object and scope<br>? ? ? ? return function() { return?$this->val; };<br>? ? }<br>}<br>$ob1?= new?A(1);<br>$ob2?= new?A(2);<br>$cl?=?$ob1->getClosure();<br>echo?$cl(),?"n"; ? ?//1<br>$cl?=?$cl->bindTo($ob2);<br>echo?$cl(),?"n"; ? ?//2<br>?></span> <code><strong><?php<br />class A {<br /> function __construct($val) {<br /> $this->val = $val;<br> }<br> function getClosure() {<br> //returns closure bound to this object and scope<br> return function() { return $this->val; };<br> }<br>}$ob1 = new A(1);<br>$ob2 = new A(2);<br>$cl = $ob1->getClosure();<br>echo $cl() , "n"; //1<br>$cl = $cl->bindTo($ob2);<br>echo $cl(), "n"; //2<br>?> <span></span></strong> 17. Context options and parameters
The socket context option is available for all wrapper protocols that work over sockets, like tcp, http and ftp
.<code><span><?php<br />// connect to the internet using the '192.168.0.100' IP<br />$opts = array(<br /> 'socket' => array(<br>? ? 'bindto'?=>?'192.168.0.100:0',<br>? ? ),<br>);<br>// connect to the internet using the '192.168.0.100' IP and port '7000'<br>$opts?= array(<br>? ? 'socket'?=> array(<br>? ? 'bindto'?=>?'192.168.0.100:7000',<br>? ? ),<br>);<br>// connect to the internet using port '7000'<br>$opts?= array(<br>? ? 'socket'?=> array(<br>? ? 'bindto'?=>?'0:7000',<br>? ? ),<br>);<br>// create the context...<br>$context?=?stream_context_create($opts);<br>// ...and use it to fetch the data<br>echo?file_get_contents('http://www.example.com',?false,?$context);<br>?></span><code><span><?php<br />// connect to the internet using the '192.168.0.100' IP<br />$opts = array(<br /> 'socket' => array( 'bindto' => '192.168.0.100:0',<br> ),<br>);<br>// connect to the internet using the '192.168.0.100' IP and port ' 7000'<br>$opts = array(<br> 'socket' => array(<br> 'bindto' => '192.168.0.100:7000',<br> ),<br>);<br>// connect to the internet using port '7000'<br>$opts = array(<br> 'socket' => array(<br> 'bindto' => ' 0:7000',<br> ),<br>);<br>// create the context...<br>$context = stream_context_create($opts);<br>// .. .and use it to fetch the data<br>echo file_get_contents('http://www.example.com', false, $context);<br>?><em></em></span> HTTP context options — A list of options for the HTTP context. Context options provided for the http:// and
https:// transport protocols. transports. Optional options:- <code>methodstring The remote server supports <code>GET, <code>POST or other HTTP methods. The default value is <code>GET.
- <code>headerstring Extra header sent during request. The value in this option will override other values ??(such as User-agent:, Host: and Authentication:).
- <code>user_agentstring The value of the header User-Agent: to be sent. If no user-agent is specified in the header context option above, this value will be used. By default, the user_agent set in php.ini is used.
- <code>contentstring Extra data to be sent after the header. Typically using POST or PUT requests.
- <code>proxystring URI The address of the proxy server specified. (e.g. tcp://proxy.example.com:5100).
- <code>request_fulluriboolean when set to <code>TRUE , the entire URI will be used when constructing the request. (i.e. GET http://www.example.com/path/to/file.html HTTP/1.0). Although this is a non-standard request format, some proxy servers require it. The default value is <code>FALSE.
- <code>follow_locationinteger follows the redirect of the Location header. Set to 0 to disable. The default value is 1.
- <code>max_redirectsinteger The maximum number of redirects to follow. A value of 1 or less means no redirects will be followed. The default value is 20.
- <code>protocol_versionfloat HTTP protocol version. The default value is 1.0. Versions prior to PHP 5.3.0 did not implement chunked transfer decoding. If this value is set to 1.1 , compatibility with 1.1 will be your responsibility.
- <code>timeoutfloat read timeout, in seconds (s), specified with float (e.g. 10.5). By default, the default_socket_timeout set in php.ini is used.
- <code>ignore_errorsboolean still gets the content even if there is a fault status code. The default value is <code>FALSE.
FTP context options — FTP context option listing
SSL Context Options — List of SSL context options. ssl:// and tls:// transport protocol context options list. Options: Many.
CURL context options — CURL context options list. CURL context options are available when the CURL extension is compiled (via the --with-curlwrappers configure option). Optional options:
- <code>methodstring <code>GET, <code>POST, or other HTTP methods supported by the remote server. Defaults to <code>GET.
- <code>headerstring Additional request headers. This value will override the value set through other options (such as: User-agent:, Host:, , Authentication:).
- <code>user_agentstring Sets the value of the User-Agent header in the request. The default is the user_agent setting in php.ini.
- <code>contentstring Extra data sent after the header. This option is not used in <code>GET and <code>HEAD requests.
- <code>proxystring URI, used to specify the address of the proxy server (for example tcp://proxy.example.com:5100).
- <code>max_redirectsinteger The maximum number of redirects. 1 or smaller means the redirect will not be followed. The default is 20.
- <code>curl_verify_ssl_hostboolean verification server. Default is <code>FALSE。This option is available in both HTTP and FTP protocols.
- <code>curl_verify_ssl_peerboolean Requires verification of the SSL certificate used. Default is <code>FALSE。This option is available in both HTTP and FTP protocols. Get a page and send data as POST:
<code><span><?php<br />$postdata = http_build_query(<br /> array(<br /> 'var1' =>?'some content',<br>? ? ? ? 'var2'?=>?'doh'<br>? ? ? ? )<br>);<br>$opts?= array('http'?=><br>? ? array(<br>? ? ? ? 'method'?=>?'POST',<br>? ? ? ? 'header'?=>?'Content-type: application/x-www-form-urlencoded',<br>? ? ? ? 'content'?=>?$postdata<br>? ? ? ? )<br>);<br>$context?=?stream_context_create($opts);<br>$result?=?file_get_contents('http://example.com/submit.php',?false,?$context);<br>?></span>
Phar context options — List of Phar context options. phar:// Context options for the wrapper. Optional: <code>compressint One of Phar compression constants. <code>metadatamixed Phar metadata. See Phar::setMetadata().
Context parameter — Context parameter list. These parameters (parameters) can be set to the context returned by the function stream_context_set_params(). Parameters: <code>notificationcallable When an event occurs on a stream, the callable will be called.
18. Supported protocols and encapsulation protocols
file:// — access the local file system. Filesystem is the default wrapper protocol used by PHP and exposes the local filesystem. When a relative path is specified (a path that does not begin with /, , \, or a Windows drive letter) the path provided will be based on the current working directory. In many cases this is the directory where the script resides, unless it has been modified. When using the CLI, the directory defaults to the directory where the script is called.
In certain functions, such as fopen() and file_get_contents(), include_path is optionally searched, also as a relative path.
屬性 | 支持 |
---|---|
受 allow_url_fopen 影響 | No |
允許讀取 | Yes |
允許寫入 | Yes |
允許添加 | Yes |
允許同時(shí)讀和寫 | Yes |
支持 stat() | Yes |
支持 unlink() | Yes |
支持 rename() | Yes |
支持 mkdir() | Yes |
支持 rmdir() | Yes |
http:// -- https:// — Access HTTP(s) URL. Allows read-only access to a file or resource via the HTTP 1.0 GET method. HTTP requests will be accompanied by a Host: header for compatibility with domain name-based virtual hosts. If the user_agent string is configured in your php.ini file or byte stream context, it will also be included in the request. The data stream allows reading the body of the resource, and the headers are stored in the $http_response_header variable.
If you need to know which URL the document resource comes from (after processing all redirects), you need to process the series of response headers returned by the data flow.
屬性 | 支持 |
---|---|
受 allow_url_fopen 限制 | Yes |
允許讀取 | Yes |
允許寫入 | No |
允許添加 | No |
允許同時(shí)讀和寫 | N/A |
支持 stat() | No |
支持 unlink() | No |
支持 rename() | No |
支持 mkdir() | No |
支持 rmdir() | No |
屬性 | PHP 4 | PHP 5 |
---|---|---|
受 allow_url_fopen 影響 | Yes | Yes |
允許讀取 | Yes | Yes |
允許寫入 | Yes (僅支持新文件) | Yes (新文件/啟用?<code>overwrite?后已存在的文件) |
允許添加 | No | Yes |
允許同時(shí)讀和寫 | No | No |
支持 stat() | No | 自 5.0.0 起:僅僅 filesize()、 filetype()、 file_exists()、 is_file() 和 is_dir()。 自 PHP 5.1.0 起: filemtime()。 |
支持 unlink() | No | Yes |
支持 rename() | No | Yes |
支持 mkdir() | No | Yes |
支持 rmdir() | No | Yes |
Properties | PHP 4 | PHP 5 |
---|---|---|
Affected by allow_url_fopen | Yes | Yes |
Allow reading | Yes | Yes |
Allow writing | Yes (only supports new files) | Yes (new file/existing file after enabling <code>overwrite) |
Allow adding | No | Yes |
Allow simultaneous reading and writing | No | No |
Support stat() | No | Since 5.0.0: only filesize(), filetype(), file_exists(), is_file() and is_dir(). Since PHP 5.1.0: filemtime(). |
Support unlink() | No | Yes |
Support rename() | No | Yes |
Support mkdir() | No | Yes |
Support rmdir() | No | Yes |
php:// — Access various input/output streams (I/O streams). PHP provides a number of miscellaneous input/output (IO) streams that allow access to PHP's input and output streams, standard input, output, and error descriptors, in-memory, disk-backed temporary file streams, and filters that can operate on other read-write file resources. device.
php://stdin, php://stdout and php://stderr allow direct access to the corresponding input of the PHP process or Output stream. The data stream references the copied file descriptor, so if you open php://stdin and then close it, you only close the copy and the real referenced <code>STDIN Not affected. Note that PHP's behavior in this area was buggy until PHP 5.2.1. It is recommended that you simply use the constants <code>STDIN, <code>STDOUT and <code>STDERR instead of opening these wrappers manually.
php://stdin is read-only, php://stdout and php://stderr are write-only.
php://input is a read-only stream that provides access to the requested raw data. In the case of POST requests, it is better to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on the specific php.ini command. Moreover, in this case $HTTP_RAW_POST_DATA is not populated by default, potentially requiring less memory than activating always_populate_raw_post_data. enctype="multipart/form-data" When php://input is invalid.
php://output is a write-only data stream that allows you to write to the output buffer in the same way as print and echo.
php://fd allows direct access to the specified file descriptor. For example, php://fd/3 refers to file descriptor 3.
php://memory and php://temp is a file-like wrapper data stream that allows reading and writing temporary data. The only difference between the two is that php://memory always stores data in memory, while php://temp will store data after the amount of memory reaches a predefined limit (default is 2MB) and stored in a temporary file. The temporary file location is determined in the same way as sys_get_temp_dir(). The memory limit of php://temp can be controlled by adding /maxmemory:NN. NN is the maximum data in bytes retained in memory. If the amount is exceeded, a temporary file will be used.
php://filter is a meta-wrapper designed for filtering applications when a data stream is opened. This is useful for all-in-one file functions like readfile(), file(), and file_get_contents(), where there is no opportunity to apply additional filters before the stream contents are read. The php://filter target uses the following parameters as part of its path. Composite filter chains can be specified on a path.
屬性 | 支持 |
---|---|
首先于 allow_url_fopen | No |
首先于 allow_url_include | 僅?php://input、?php://stdin、?php://memory?和?php://temp。 |
允許讀取 | 僅?php://stdin、?php://input、?php://fd、?php://memory?和?php://temp。 |
允許寫入 | 僅?php://stdout、?php://stderr、?php://output、?php://fd、?php://memory?和php://temp。 |
允許追加 | 僅?php://stdout、?php://stderr、?php://output、?php://fd、?php://memory?和php://temp(等于寫入) |
允許同時(shí)讀寫 | 僅?php://fd、?php://memory?和?php://temp。 |
支持 stat() | 僅?php://memory?和?php://temp。 |
支持 unlink() | No |
支持 rename() | No |
支持 mkdir() | No |
支持 rmdir() | No |
僅僅支持 stream_select() | php://stdin、?php://stdout、?php://stderr、?php://fd?和?php://temp。 |
zlib:// -- bzip2:// -- zip:// — Compressed stream. zlib: PHP 4.0.4 - PHP 4.2.3 (only supports systems with fopencookie)
compress.zlib:// and compress.bzip2:// PHP 4.3.0 and above
zlib: functions like gzopen(), but its data stream can also be used by fread() and other file system functions. This is deprecated since PHP 4.3.0 as it will be confused with other file names with ":" characters; please use compress.zlib:// instead.
compress.zlib://, compress.bzip2:// are equal to gzopen() and bzopen(). And can be used on systems that don't support fopencookie.
ZIP extension registered zip: encapsulation protocol. Optional options
- compress.zlib://file.gz
- compress.bzip2://file.bz2
- zip://archive.zip#dir/file.txt
data:// — data (RFC 2397). Usage: data://text/plain;base64,
屬性 | 支持 |
---|---|
受限于 allow_url_fopen | No |
受限于 allow_url_include | Yes |
允許讀取 | Yes |
允許寫入 | No |
允許追加 | No |
允許同時(shí)讀寫 | No |
支持 stat() | No |
支持 unlink() | No |
支持 rename() | No |
支持 mkdir() | No |
支持 rmdir() | No |
Print the contents of data://:
<code><code>// 打印 "I love PHP"echo file_get_contents('data://text/plain;base64,SSBsb3ZlIFBIUAo=');
?>//Print "I love PHP"
echo file_get_contents('data://text/plain;base64,SSBsb3ZlIFBIUAo=');
? > Get media type: <code><span><?php<br />$fp = fopen('data://text/plain;base64,', 'r');<br />$meta = stream_get_meta_data($fp);<br />echo $meta['mediatype']; // 打印 "text/plain"<br />?></span> <code><p><?php<br />$fp = fopen('data://text/plain;base64,', 'r');<br />$meta = stream_get_meta_data($fp); <br />echo $meta['mediatype']; // Print "text/plain"<br />?><span></span></p> glob:// — Find matching file path patterns. Usage: glob://
Attributes | Supported |
---|---|
Subject to allow_url_fopen | No |
Subject to allow_url_include | No |
Allow reading | No |
Allow writing | No |
Allow appending | No |
Allow simultaneous reading and writing | No |
Support stat() | No |
Support unlink() | No |

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach
