This article shows you the full reference of PHP. It is very detailed and has examples. It is a very good article and is recommended for reference by friends in need.
What is a reference
Quoting in PHP means accessing the same variable content with different names. This is not like a C pointer; instead, the reference is a symbol table alias. Note that in PHP, variable names and variable contents are different, so the same content can have different names. The closest analogy is Unix's filenames and the files themselves - the variable names are the directory entries, and the variable contents are the files themselves. References can be thought of as hardlinks in Unix file systems.
What does a reference do
PHP’s reference allows two variables to point to the same content. Meaning, when doing this:
The code is as follows:
<?php $a =& $b; ?>
This means that $a and $b point to the same variable.
Note:
$a and $b are exactly the same here. It’s not that $a points to $b or vice versa, but that $a and $b point to the same place. .
Note:
If an array with a reference is copied, its value will not be dereferenced. The same is true for passing array values to functions.
Note:
If an undefined variable is assigned by reference, passed by reference parameter, or returned by reference, the variable will be automatically created.
Example #1 Using references to undefined variables
The code is as follows:
<?php 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 operation In the symbol (PHP 4.0.4 and later versions):
The code is as follows:
<?php $bar =& new fooclass(); $foo =& find_var($bar); ?>
Since PHP 5, new automatically returns a reference, so using =& here is obsolete and will generate E_STRICT level messages.
Note:
Not using the & operator causes a copy of the object to be generated. If you use $this in a class, it will apply to the current instance of that class. Assignment without & will copy the instance (e.g. object) and $this will act on the copy, which is not always the desired result. Due to performance and memory consumption issues, you usually only want to work on one instance.
Although you can use the @ operator to suppress any error messages in the constructor, such as @new, this has no effect when using the &new statement. This is a limitation of the Zend engine and will cause a parsing error.
Warning
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.
Example #2 Reference global variables within a function
The code is as follows:
<?php $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' ?>
Treat global $var; as $var =& $GLOBALS['var']; abbreviation. Thus assigning another reference to $var only changes the reference to the local variable.
Note:
If a variable with a reference is assigned a value in a foreach statement, the referenced object is also changed.
Example #3 Reference and foreach statement
The code is as follows:
<?php $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 to 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:
The code is as follows:
<?php function foo(&$var){ $var++; } $a=5;foo($a); ?>
will change $a to 6. This is because in function foo the variable $var points to the same thing that $a points to. See Passing by Reference for a more detailed explanation.
The third thing a reference does is reference return.
What a reference is not
As mentioned before, a reference is not a pointer. This means that the following structure will not produce the expected effect:
The code is as follows:
<?php function foo(&$var) { $var =& $GLOBALS["baz"]; } foo($bar); ?>
This will make the $var variable in the foo function bound to $bar when the function is called. , but then was re-bound to $GLOBALS["baz"]. It is not possible to bind $bar to another variable within the function call scope through the reference mechanism, because there is no variable $bar in function foo (it is represented as $var, but $var only has the variable content and no call symbol table name-to-value binding). You can use reference returns to reference variables selected by the function.
Passing by reference
You can pass a variable by reference to a function so that the function can modify the value of its parameter. The syntax is as follows:
The code is as follows:
<?php 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 correctly by reference. In recent versions of PHP, if you use & in foo(&$a); you will get a warning that "Call-time pass-by-reference" is deprecated.
The following can be passed by reference:
Variables, such as foo($a)
New statements, such as foo(new foobar())
References returned from functions , for example:
The code is as follows:
<?php function &bar() { $a = 5; return $a; } foo(bar()); ?>
For detailed explanation, see reference return.
Any other expression cannot be passed by reference, and the result is undefined. For example, the following example of passing by reference is invalid:
The code is as follows:
<?php function bar() // Note the missing & { $a = 5; return $a; } foo(bar()); // 自 PHP 5.0.5 起导致致命错误 foo($a = 5) // 表达式,不是变量 foo(5) // 导致致命错误 ?>
These conditions are available in PHP 4.0.4 and later versions.
引用返回
引用返回用在当想用函数找到引用应该被绑定在哪一个变量上面时。不要用返回引用来增加性能,引擎足够聪明来自己进行优化。仅在有合理的技术原因时才返回引用!要返回引用,使用此语法:
代码如下:
<?php class foo { public $value = 42; public function &getValue() { return $this->value; } } $obj = new foo; $myValue = &$obj->getValue(); // $myValue is a reference to $obj->value, which is 42. $obj->value = 2; echo $myValue; // prints the new value of $obj->value, i.e. 2. ?>
本例中 getValue 函数所返回的对象的属性将被赋值,而不是拷贝,就和没有用引用语法一样。
Note: 和参数传递不同,这里必须在两个地方都用 & 符号——指出返回的是一个引用,而不是通常的一个拷贝,同样也指出 $myValue 是作为引用的绑定,而不是通常的赋值。
Note: 如果试图这样从函数返回引用:return ($this->value);,这将不会起作用,因为在试图返回一个表达式的结果而不是一个引用的变量。只能从函数返回引用变量——没别的方法。如果代码试图返回一个动态表达式或 new 运算符的结果,自 PHP 4.4.0 和 PHP 5.1.0 起会发出一条 E_NOTICE 错误。
代码如下:
<?php function &test(){ static $b=0;//申明一个静态变量 $b=$b+1; echo $b; return $b; } $a=test();//这条语句会输出$b的值为1 $a=5; $a=test();//这条语句会输出$b的值为2 $a=&test();//这条语句会输出$b的值为3 $a=5; $a=test();//这条语句会输出$b的值为6 ?>
$a=test()方式调用函数,只是将函数的值赋给$a而已,而$a做任何改变化,都不会影响到函数中的$b,而通过$a=&test()方式调用函数呢, 他的作用是将return $b中的$b变量的内存地址与$a变量的内存地址指向了同一个地方,即产生了相当于这样的效果($a=&b;) 所以改变$a的值,也同时改变了$b的值,所以在执行了 $a=&test(); $a=5; 以后,$b的值变为了5。
取消引用
当 unset 一个引用,只是断开了变量名和变量内容之间的绑定。这并不意味着变量内容被销毁了。例如:
代码如下:
<?php $a = 1; $b =& $a; unset($a); ?>
不会 unset $b,只是 $a。
再拿这个和 Unix 的 unlink 调用来类比一下可能有助于理解。
引用定位
许多 PHP 的语法结构是通过引用机制实现的,所以上述有关引用绑定的一切也都适用于这些结构。一些结构,例如引用传递和返回,已经在上面提到了。其它使用引用的结构有:
global 引用
当用 global $var 声明一个变量时实际上建立了一个到全局变量的引用。也就是说和这样做是相同的:
代码如下:
<?php $var =& $GLOBALS["var"]; ?>
这意味着,例如,unset $var 不会 unset 全局变量。
使用unset($a)与$a=null的结果是不一样的。如果该块内存只有$a一个映射,那么unset($a)与$a=null等价,该内存的引用计数变为0,被自动回收;如果该块内存有$a和$b两个映射,那么unset($a)将导致$a=null且$b不变的情况,而$a=null会导致$a=$b=null的情况。
原因:某变量赋值为null,将导致该变量对应的内存块的引用计数直接置为0,被自动回收。
$this
在一个对象的方法中,$this 永远是调用它的对象的引用。
引用的作用
如果程序比较大,引用同一个对象的变量比较多,并且希望用完该对象后手工清除它,个人建议用 "&" 方式,然后用$var=null的方式清除. 其它时候还是用php5的默认方式吧. 另外, php5中对于大数组的传递,建议用 "&" 方式, 毕竟节省内存空间使用。
下面再来个小插曲 php中对于地址的指向(类似指针)功能不是由用户自己来实现的,是由Zend核心实现的,php中引用采用的是“写时拷贝”的原理,就是除非发生写操作,指向同一个地址的变量或者对象是不会被拷贝的。
通俗的讲
1:如果有下面的代码
代码如下:
<?ph $a="ABC"; $b=$a; ?>
其实此时,$a与$b都是指向同一内存地址,而并不是$a与$b占用不同的内存。
2:如果在上面的代码基础上再加上如下代码
代码如下:
$a="EFG";
由于$a与$b所指向的内存的数据要重新写一次了,此时Zend核心会自动判断 自动为$b生产一个$a的数据拷贝,重新申请一块内存进行存储。
总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。
相关推荐:
The above is the detailed content of The meaning and usage of PHP quotes. For more information, please follow other related articles on the PHP Chinese website!

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor