


Detailed introduction to PHP variable reference and object reference_PHP tutorial
The article summarizes how to make variable references in PHP and what are variable references? How to do it? Let’s introduce the usage of PHP variable references one by one.
What does a quote do
PHP's references allow two variables to point to the same content. Meaning, when doing this:
The code is as follows | Copy code |
代码如下 | 复制代码 |
$a =& $b; ?> |
?>
This means $a and $b point to the same variable.
$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, or returned by reference, the variable will be automatically created.
Example #1 Using references to undefined variables
代码如下 | 复制代码 |
function foo(&$var) { } foo($a); // $a is "created" and assigned to null $b = array(); $c = new StdClass;
|
The code is as follows | Copy code | ||||||||
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 code is as follows | Copy code |
$bar =& new fooclass(); $foo =& find_var($bar); ?> |
The code is as follows | Copy code |
$a="ABC"; $b =&$a; echo $a;//Output here: ABC echo $b;//Output here: ABC $b="EFG"; echo $a;//The value of $a here becomes EFG, so EFG is output echo $b;//Output EFG here ?> |
Function call by address
I won’t go into details about call by address. The code is given directly below
The code is as follows | Copy code | ||||||||
{ $a=$a+100;
}
echo " |
It should be noted that if test(1); is used here, an error will occur. You have to think about the reason yourself
Function reference returns
Let’s look at the code first
The code is as follows | Copy code | ||||
function &test() { static $b=0;//Declare a static variable $b=$b+1; echo $b; return $b; }$a=test();//This statement will output that the value of $b is 1 $a=5; $a=test();//This statement will output that the value of $b is 2
|
The code is as follows | Copy code |
class a{ var $abc="ABC"; } $b=new a; $c=$b; echo $b->abc;//Output ABC here echo $c->abc;//Output ABC here $b->abc="DEF"; echo $c->abc;//Output DEF here ?> |
The above code is the effect of running in PHP5
In PHP5, object copying is achieved through references. In the above column, $b=new a; $c=$b; is actually equivalent to $b=new a; $c=&$b;
The default in PHP5 is to call objects by reference, but sometimes you may want to create a copy of the object and hope that changes to the original object will not affect the copy. For this purpose, PHP defines a special method called __clone .
The role of quotation
If the program is relatively large, there are many variables referencing the same object, and you want to clear it manually after using the object, I personally recommend using the "&" method, and then using $var=null to clear it. Otherwise, use the default of php5 Method. In addition, for transferring large arrays in php5, it is recommended to use the "&" method, after all, it saves memory space.
Unquote
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. For example:
The code is as follows | Copy code | ||||
unset ($a); |
代码如下 | 复制代码 |
$var =& $GLOBALS["var"]; ?> |
When you declare a variable with global $var you actually create a reference to the global variable. That is the same as doing this:
The code is as follows | Copy code |
$var =& $GLOBALS["var"]; ?> |
This means that, for example, unset $var will not unset a global variable.
$this
In an object method, $this is always a reference to the object that calls it.
//Another little episode below
The address pointing (similar to a pointer) function in PHP is not implemented by the user himself, but is implemented by the Zend core. The reference in PHP adopts the principle of "copy on write", that is, unless a write operation occurs, it points to the same address. Variables or objects will not be copied.
In layman terms
1: If there is the following code$a="ABC";
$b=$a;
In fact, at this time, $a and $b both point to the same memory address, rather than $a and $b occupying different memories
2: If you add the following code to the above code
Since the data in the memory pointed to by $a and $b needs to be rewritten, the Zend core will automatically determine at this time and automatically generate a data copy of $a for $b and re-apply for a piece of memory for storage
代码如下 | 复制代码 |
$var1 = "Example variable"; function global_references($use_globals) global_references(false); |
The code is as follows | Copy 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 shorthand for $var =& $GLOBALS['var'];. Thus assigning another reference to $var only changes the reference to the local variable.
Let’s look at an interview question below
PHP interview questions are as follows:
The code is as follows
|
Copy code
|
||||
$a = 1;
$x =&$a; |
The answers to php interview questions are as follows:
true
APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

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

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

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

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

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

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor
