Home >Backend Development >PHP Tutorial >PHP Chinese Manual 2

PHP Chinese Manual 2

WBOY
WBOYOriginal
2016-07-30 13:31:541062browse

<code><code>

11. Exception handling

<code><code>

Users can extend PHP’s built-in exception handling class with a custom exception handling class. 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><?php<br />class Exception{<br />protected $message = 'Unknown exception'; //Exception information<br />protected $code = 0; //User-defined exception code<br />protected $ file; //The name of the file where the exception occurred<br />protected $line; //The line number of the code where the exception occurred<br />function __construct($message = null, $code = 0);<br />final function getMessage(); //Return the exception message<br /> final function getCode(); // Returns the exception code<br />final function getFile(); // Returns the file name where the exception occurred<br />final function getLine(); // Returns the code line number where the exception occurred<br />final function getTrace(); / / backtrace() array<br />final function getTraceAsString(); // getTrace() information that has been formatted into a string<br />/* Overloadable method*/<br />function __toString(); // Outputable string<br />} <br />?>

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 all variables Whether it has been assigned a value. 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 />//Customize an exception handling class<br />class MyException extend s Exception{ // Heavy Define the constructor to make message a property that must be specified <br /> public function __construct($message, $code = 0) {<br />                     // Customized code   //                                                                                                                            . , $code);<br />}<br />// Customize the style of string output<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><br>//<span>Create a class for testing the exception handling mechanism</span>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>// Throw a custom exception<br>throw new MyException('1 is an invalid parameter', 5);<br>break;<br>case self::THROW_DEFAULT:<br>// Throw a default exception<br>throw new Exception('2 isnt allowed as a parameter', 6);<br>break;<br>default:<br>// Create an object without exception <br>$this->var = $avalue;<br>break;<br>}<br>}<br>}<br>// Example 1<br> try {<br>$o = new TestException(TestException::THROW_CUSTOM);<br>} catch (MyException $e) { // Catch exception<br>echo "Caught my exceptionn", $e;<br>$e->customFunction();<br> } catch (Exception $e) { // Ignored<br>echo "Caught Default Exceptionn", $e;<br>}<br>// Execute subsequent code<br>var_dump($o);<br>echo "nn";<br>// Example 2<br> try {<br>$o = new TestException(TestException::THROW_DEFAULT);<br>} catch (MyException $e) { // Unable to match the exception type, ignored<br>echo "Caught my exceptionn", $e;<br>$e-&gt ;customFunction();<br>} catch (Exception $e) { //Catch the exception<br>echo "Caught Default Exceptionn", $e;<br>}<br>//Execute subsequent code<br>var_dump($o);<br>echo "nn"; <br>//Example 3<br>try {<br>$o = new TestException(TestException::THROW_CUSTOM);<br>} catch (Exception $e) { //Catch exception<br>echo "Default Exception caughtn", $e;<br>}<br>// Execute subsequent code<br>var_dump($o);<br>echo "nn";<br>// Example 4<br>try {<br>$o = new TestException();<br>} catch (Exception $e) { // No exception, ignored<br> echo "Default Exception caughtn", $e;<br>}<br>//Execute subsequent code<br>var_dump($o);<br>echo "nn";<br>?><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 either 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 <= ) }}} Else {<br /> if ($ Step & GT; = 0) {<br /> Throw New LogiceXception ('Step Must be -ve'); i += $step) {<br />                                                                                                                  yield $i; 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 />?><br><br><br><br><br><br><br><br><br><br><br><br><br><pre class="brush:php;toolbar:false">Single digit odd numbers from range(): 1 3 5 7 9 Single digit odd numbers from xrange(): 1 3 5 7 9 </pre> <br>

For example, the following function and class are equivalent:

function getLinesFromFile($fileName) {

if (!$fileHandle = fopen($fileName, 'r')) {U Return;}}

while (FALSE! == $ LINE = FGETS ($ Filehandle)) {

yield $ line;

}

Fclose ($ filehandle); Ator Implements Iterator {

protected $fileHandle;

protected $line;

protected $i;

public function __construct($fileName) {

if (!$this->fileHandle = fopen($fileName, 'r')) {

throw New Runtimeexception ('COULDN'TOPEN FILE "'. $ FILENAMAME. '" "); $ This- & gt; line = fgets($this->fileHandle);

$this->i = 0;

}

public function valid() {

return false !== $this->line; } public function current () {                                               use using using using using   using   using     using     through using     out out out through out out through Through out through  ‐     ‐ ‐ ‐‐‐‐ and ‐ to ;line) {

                                                                                                                                                                                                   ; Handle );

                                                         <code><code>

<code><?php<br />$a =& $b; //This means <var><var>$a</var></var> and <var><var>$b</var></var> point to the same variable. <var><var> $ a</var></var> and <var><var> $ B</var></var> are exactly the same here. This is not <var><var> $ a</var></var> to point to $ b<var><var> or · // </var> and </var><var>$b<var></var> point to the same place. </var>?><var><var></var></var><br>

<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();

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):

< ?php

$bar =& new fooclass();

$foo =& find_var($bar);

?><code><span><br><br><br></span>

If a declaration is given inside a function The variable of

global

is assigned a reference, which is only visible inside the function. This can be avoided by using the

$GLOBALS array. Quote global variables in the function:

& lt ;? PHP

$ var1 = "example variable";

$ var2 = "" ";

Function global_references ($ use_globals) { <code> global $var1, $var2;<span> if (!$use_globals) {<br> $var2 =& $var1; // visible only inside the function<br> } else {<br> $GLOBALS["var2"] =& $var1; // visible also in global context<br> }<br>}<br>global_references(false);<br>echo "var2 is set to '$var2'n"; // var2 is set to ''<br>global_references(true);<br>echo "var2 is set to '$var2'n"; // var2 is set to 'Example variable'<br>?> GLOBALS['var']; Abbreviation for <br>. Thus assigning other references to <br>$var<br> only changes the reference of the local variable. <br><br></span>

If you assign a value to a variable with a reference in the 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 it by reference variable. This is accomplished by creating a local variable within the function and that variable references the same content in the calling scope. For example:

function foo(&$var){

$var++;

}

$a=5;

foo($a);

?> ;

will make

$a<code><span> become 6. This is because the variable <br /><br />$var<br /><br /> in the <br /><br />foo</span> function points to the same content as

$a

. See Passing by Reference for a more detailed explanation.

The third thing that references do is reference returns. References are not pointers.

You can pass a variable to a function by reference so that the function can modify the value of its parameter.

function foo(&$var){

$var++;

}

$a=5;

foo($a);// $a is 6 here

?>

Note that there are no reference symbols in the function call - only in the function definition. The function definition alone is enough for parameters to be passed by reference correctly

<code><span><br><br><br><br><br>The following can be passed by reference:<br></span><p><span>Variables, such as <em>foo($a); </em>New statements, such as <em>foo(new foobar()); </em>References returned from functions</span></p> <p></p> <p></p> <p></p> <p><span>Any other expression cannot be passed by reference, The result is undefined. </span></p>

<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 />?></span>

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 case getValue The properties of the object returned by the function will be assigned instead of copied, just like without reference syntax. 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><span><?php<br />$a = 1;<br />$b =& $a;<br />unset($a);<br />? ></span>

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:

<code><span><?php<br />$var =& $GLOBALS["var"]; //This means, for example, unset <var><var>$var </var></var> Will not 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 Meaning they are available in all scopes of a script. They can be accessed within a function or method without executing global $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.

$GLOBALS - References all variables available in the global scope. A global combination array that contains all variables. The name of the variable is the key of the array.

function test() {

$foo = "local variable";

echo '$foo in global scope: ' . $GLOBALS["foo "] . "n";//$foo in global scope: Example content

echo '$foo in current scope: ' . $foo . "n";//$foo in current scope: local variable

}<code>$foo = "Example content";test();
?>






"Superglobal" is also called an automated global variable. 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. Items in this array are represented by

Web server creation. You may or may not be able to find the following elements in $_SERVER. Enumeration:

'PHP_SELF': The file name of the currently executing script, related to the document root. For example, using

$_SERVER['PHP_SELF'] in a script at http://example.com/test.php/foo.bar 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 $_SERVER group.

Since variables in $_REQUEST are passed to script files via GET, POST and COOKIE input mechanisms, they can be It cannot be tampered with letter. 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 to 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. Please 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: An 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 that the track_errors configuration item is 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><span><?php<br />@strpos();<br />echo $php_errormsg; //Wrong parameter count for strpos()<br />?></span>

$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_respon se_header);<br />}<br />get_contents ();<br />var_dump($http_response_header);<br />?></span>

$argc — The number of arguments passed to the script: Contains the number of arguments passed to the current script when running from the command line The number of parameters for the script. The file name of the script is always passed as an argument to the current script, so the minimum value of $argc is 1. This variable is only available when register_argc_argv is turned on.

$argv — Array of arguments passed to the script: An array containing the arguments passed to the current script when running from the command line. The first parameter is always the file name of the current script, so $argv[0] is the script file name. This variable is only available when register_argc_argv is turned on. +

Exception is for all exceptions base class. Class summary:

Exception {

/* Attributes*/

protectedstring

$ message

; protectedint$

code

;

protectedstring$file

;

protectedint$line;

/* method*/ public__construct ([ string$message = " " [, int

$code

= 0 [, Exception$previous = NULL ]]] )

finalpublicstringgetMessage ( void ) finalpublicExceptiongetPrevious ( void )

finalpublicintgetCode (void)

finalpublicstringgetFile (void) finalpublicintgetLine (void) finalpublicarraygetTrace(void) finalpublicstringgetTraceAsString ( void )<code><code> publicstring__toString ( void )<code><code> finalprivatevoid__clone ( void )

}

Attributes: message: exception message content; code: exception code; file: the file name where the exception was thrown; line: the line number in the file where the exception was thrown

Exception::__construct — Exception constructor

Parameters: message: The thrown exception message content. code: exception code. previous: The previous exception in the exception chain.

Exception::getMessage — Get the exception message content

Parameters: This function has no parameters.

Exception::getPrevious — Returns the previous exception in the exception chain

参数:Exception::getPrevious — 返回异常链中的前一个异常。追踪异常,并循环打印。

<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 — 获取异常代码

参数:此函数没有参数。

Exception::getFile — 获取发生异常的程序文件名称

参数:此函数没有参数。

Exception::getLine — 获取发生异常的代码在文件中的行号

参数:此函数没有参数。

Exception::getTrace — 获取异常追踪信息

参数:此函数没有参数。

Exception::getTraceAsString — 获取字符串类型的异常追踪信息

参数:此函数没有参数。

Exception::__toString — 将异常对象转换为字符串

参数:此函数没有参数。

Exception::__clone — 异常克隆

参数:此函数没有参数。没有返回值,异常被不允许克隆。

ErrorException::__construct — 异常构造函数

参数:message:抛出的异常消息内容。code:异常代码。severity:异常的严重级别。filename:抛出异常所在的文件名。lineno:抛出异常所在的行号。previous:异常链中的前一个异常。

ErrorException::getSeverity — 获取异常的严重程度

参数:此函数没有参数。

<code><span><?php<br />try {<br /> throw new ErrorException("Exception message", 0, 75);<br />} catch(ErrorException $e) {<br /> echo "This exception severity is: " . $e->getSeverity();<br>}<br>?></span>

16.预定义接口

Traversable(遍历)接口:

检测一个类是否可以使用 foreach 进行遍历的接口。无法被单独实现的基本抽象接口。相反它必须由 IteratorAggregate 或 Iterator 接口实现。实现此接口的内建类可以使用 foreach 进行遍历而无需实现 IteratorAggregate 或 Iterator 接口。这是一个无法在 PHP 脚本中实现的内部引擎接口。IteratorAggregate 或 Iterator 接口可以用来代替它。

Traversable { }    这个接口没有任何方法,它的作用仅仅是作为所有可遍历类的基本接口。

Iterator(迭代器)接口:

可在内部迭代自己的外部迭代器或类的接口。

IteratorextendsTraversable {

    /* 方法 */

    abstractpublicmixedcurrent ( void )

    abstractpublicscalarkey ( void )

    abstractpublicvoidnext ( void )

    abstractpublicvoidrewind ( void )

    abstractpublicbooleanvalid ( void )

}

Iterator::current — 返回当前元素:没有参数,可返回任何类型。

Iterator::key — 返回当前元素的键:没有参数,成功返回标量,失败则返回null。

Iterator::next — 向前移动到下一个元素:没有参数,任何返回都将被忽略。此方法在 foreach 循环之后被调用。

Iterator::rewind — 返回到迭代器的第一个元素:当开始一个 foreach 循环时,这是第一个被调用的方法。它将会在 foreach 循环之后被调用。没有参数,任何返回都将被忽略。

Iterator::valid — 检查当前位置是否有效:此方法在 Iterator::rewind() 和 Iterator::next() 方法之后被调用以此用来检查当前位置是否有效。没有参数,返回将被转换为布尔型。成功时返回 <code>TRUE, 或者在失败时返回 <code>FALSE。

IteratorAggregate::getIterator — 获取一个外部迭代器:没有参数,实现了 Iterator 或 Traversable 接口的类的一个实例。

ArrayAccess(数组式访问)接口:

提供像访问数组一样访问对象的能力的接口。

ArrayAccess {

    /* 方法 */

    abstractpublicbooleanoffsetExists ( mixed<code>$offset )

    abstractpublicmixedoffsetGet ( mixed<code>$offset )

    abstractpublicvoidoffsetSet ( mixed<code>$offset , mixed<code>$value )

    abstractpublicvoidoffsetUnset ( mixed<code>$offset )

}

ArrayAccess::offsetExists — 检查一个偏移位置是否存在:对一个实现了 ArrayAccess 接口的对象使用 isset() 或 empty() 时,此方法将执行。当使用 empty() 并且仅当 ArrayAccess::offsetExists() 返回 <code>TRUE 时,ArrayAccess::offsetGet() 将被调用以检查是为否空。参数:offset 需要检查的偏移位置。成功时返回 <code>TRUE, 或者在失败时返回 <code>FALSE。如果一个非布尔型返回值被返回,将被转换为布尔型。

<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 — 获取一个偏移位置的值:当检查一个偏移位置是否为 empty() 时,此方法被执行。

Parameter: offset The offset position to be obtained. Return value: Any type can be returned.

ArrayAccess::offsetSet — Set the value of an offset position: Parameter: offset The offset position to be set. value The value that needs to be set. There is no return value.

If another value is not available, then the <code>offset parameter will be set to <code>NULL.

ArrayAccess::offsetUnset — Resets the value of an offset position: This method will not be called when (unset) is used for type conversion.

<code>Parameter: offset The offset position to be reset. No return value.

Serialization interface:

Serializable::serialize — String representation of the object. This method plays the role of object destructor. After this method, the __destruct() method will not be called. This function has no parameters and returns a string representation of the object or <code>NULL.

Serializable::unserialize — Construct object. This method plays the role of object constructor. After this method, __construct() will not be called. Parameters: String representation of the serialized object.

Closure::__construct — Constructor used to disable instantiation. This method is only used to disable instantiation of an object of the Closure class. The creation method of objects of this class is written on the Anonymous Functions page. This function has no parameters and no return value.

Closure::bind — Copy a closure and bind the specified $this object to the class scope. This method is a static version of Closure::bindTo().

Parameters: 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 the class scope you want to bind to the closure, or 'static' meaning 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 $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<code>echo $bcl2() , "n"; //2<span>?><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>Closure::bindTo — Copy the current closure object and bind 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 </span>$this 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

newscope class. Static closures cannot have bound objects (the value of the newthis parameter should be set to 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

<code><span>< = $ Value; v} <br /> Function getClosure () {<br /> // return closure? <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>?><br><br><br><br><br><br></span>

17. Context options and parameters Socket context Options are available for all wrapper protocols that work over sockets, like

tcp

,

http

and

ftp. // connect to the internet using the '192.168.0.100' IP$opts = array( 'socket' => array( 'bindto' => '192.168.0.100:0', ),);// connect to the internet using the '192.168.0.100' IP and port '7000'$opts = array(

'socket' => array( 'bindto' => '192.168.0.100:7000', ), );// connect to the internet using port '7000'

$opts = array(

'socket' => array(

'bindto' => '0:7000',

),

);

// create the context...

$context = stream_context_create($opts);<code>// ...and use it to fetch the dataecho file_get_contents('http://www.example.com', false, $ context);
?>














HTTP context options — List of options for 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 Additional 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 Additional data to be sent after the header. Typically using POST or PUT requests.
<code>proxystring URI The address of the specified proxy server. (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 redirect that follows 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 get the content even if it is a fault status code. The default value is <code>FALSE.

FTP context options — FTP context option listing

SSL Context Options — SSL Context List of 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 Set the value of the User-Agent header in the request. The default is the user_agent setting in php.ini.
<code>contentstring Additional 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 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' => content' => $postdata<br> )<br>);<br>$context = stream_context_create($opts);<br>$result = file_get_contents('http://example.com/submit.php', false, $context);<br>? ><br><br><br><br></span>

Phar context options — Phar context options list.

phar://

The context option of the wrapper. Optional:

compressint One of Phar compression constants. metadatamixed Phar metadata (metadata). See Phar::setMetadata(). <code><code>

Context parameter — Context parameter list. These parameters (

parameters

) can be set to the

context returned by the function stream_context_set_params() . Parameters: notificationcallable When an event occurs on a stream, the callable will be called. <code>

18. Supported protocols and encapsulation protocols

file:// — Access 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.

Packaging protocol summary

AttributesAffected by allow_url_fopen

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.

Support
No Yes
Allow simultaneous reading and writing Yes
Support stat() Yes
Support unlink() Yes
Support rename() Yes
Support mkdir() Yes
Support rmdir() Yes
Packaging protocol summary
Attributes Support
Restricted by allow_url_fopen Yes
Allow reading Yes
Allow writing No
Allow adding No
Allow simultaneous reading and writing N/A
Support stat() No
Support unlink() No
Support rename() No
Support mkdir() No
Support rmdir() No

ftp:// -- ftps: // — Access FTP(s) URLs. Allows reading of existing files via FTP, as well as creating new files. If the server does not support passive mode FTP, the connection will fail.

After opening the file, you can both read and write, but not at the same time. When the remote file already exists on the ftp server, if you try to open and write the file without specifying the context option overwrite, the connection will fail. If you want to overwrite an existing file through FTP, specify the overwrite option of the context to open and write. Alternatively, an FTP extension can be used instead. If you set the from directive in php.ini, this value will be used as the password for anonymous ftp.

Packaging Protocol Summary
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 Write No No
supports 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 or output streams of the PHP process. 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 actual referenced <code>STDIN is 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 can access 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 rely on specific php.ini directives. Moreover, in this case $HTTP_RAW_POST_DATA is not populated by default, potentially requiring less memory than activating always_populate_raw_post_data. When enctype="multipart/form-data" is used, 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 are data streams like file wrappers that allow 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 in a temporary file after the amount of memory reaches a predefined limit (default is 2MB) . 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 amount of data retained in memory in bytes. If it exceeds, temporary files 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.

Package protocol summary (for php://filter, refer to the filtered wrapper.)
Attributes Supported
First in allow_url_fopen No
First in allow_url_include Only php://input, php://stdin, php://memory and php ://temp.
Allow reading only php://stdin, php://input, php://fd, php://memory and php:/ /temp.
Allow writing to only php://stdout, php://stderr, php://output, php://fd, php:/ /memory and php://temp.
is allowed to append only php://stdout, php://stderr, php://output, php://fd, php:// memory and php://temp (equal to write)
allow simultaneous reading and writing only php://fd, php://memory and php:/ /temp.
supports stat() only php://memory and php://temp.
Support unlink() No
Support rename() No
Support mkdir () No
Support rmdir() No
Only support stream_select() php://stdin, php://stdout, php://stderr, php://fd and 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 filenames 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: packaging protocol. Optional

  • compress.zlib://file.gz
  • compress.bzip2://file.bz2
  • zip://archive.zip#dir/file .txt

data:// — Data (RFC 2397). Usage: data://text/plain;base64,

Noecho file_get_contents('data://text/plain;base64,SSBsb3Zl
Encapsulation protocol summary
Attributes Supported
Restricted Subject to allow_url_fopen No
Subject to allow_url_include Yes
Allow reading Yes
Allow writing No
Allow append No
Allow simultaneous reading and writing No
Support stat() No
Support unlink() No
Support rename() No
Support mkdir() No
Support rmdir() // print "I love PHP"
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
Previous article:The simplest Nginx+PHPNext article:The simplest Nginx+PHP