search
HomeBackend DevelopmentPHP TutorialDetailed explanation of instances returned by PHP implementation function reference

In fact, PHP function references are the same as variable references in PHP. They both use the & symbol. So today we will take a look at some examples of function reference returns. Friends in need can refer to them. Let’s do it together. Let's see.

Reference return

The manual says this: Reference return is used when you want to use a function to find out which reference should be bound to when the variable is above. 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

When you want to bind the return reference of a function to a variable, PHP allows you to do this:

function &returns_reference()
{
  static $someref = 0;
  $someref++;
  return $someref;
}
 
$newref = &returns_reference();//引用返回,相当于 $newref = &$someref;
echo $newref; //1
//phpfensi.com
$notref = returns_reference(); //值传递的是副本
$newref = 100;
echo $notref; //2
 
$newref = 100;
echo returns_reference(); //101

It can be seen that If you want the function to return a reference, you must bring the & operator when declaring and assigning the function.

##The same is true for methods in classes:

class foo {
  public $value = 0;
 
  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;

Some simple examples

Look at the simple examples below and try to understand the reference return.

<?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
?>
//程序运行结果:
1
2
3
6

Although the function declaration method is

function &test() , we use this method $a = test( ) What the function call gets is not actually a function reference return, which is no different from an ordinary function call. PHP stipulates that what is obtained through $a = &test() is the reference return of the function.

Using the above example to explain,

$a = test() Calling a function in this way only assigns the value of the function to $a, and any changes made to $a will It will not affect $b in the function.

And when calling the function through

$a = &test() , its function is to compare the memory address of the $b variable in return $b with the $a variable The memory address points to the same place. That is to say, the effect equivalent to this is produced ($a=&$b), so changing the value of $a also changes the value of $b.

So after executing

$a = &test();

$a = 5;

, the value of $b becomes 5.

Another program example to deepen understanding:

<?php
/*
** 值传递和引用传递,值传递传递的是值的一个复本,引用传递传递的是值指向的内存地址
*/
// 函数的引用,定义时也要加上 &
function &func($a,$b){ 
 // 这里为了更直观看到效果,定义一个静态变量
 static $result = 0;  
 $result+=$a+$b;
 echo $result.&#39;<br />&#39;;
 return $result;
}
 
$a = $b = 10;
// PHP里这样写函数的引用调用,和调用普通函数没有区别(只是将函数的返回值复制给$c这个变量,$c做任何改变不会影响上面函数中的$result)
// 要记住:PHP里的函数引用定义及调用都要在函数名前加上 &
$c = func($a,$b); 
// 第一次执行func(),其静态变量$result的值变为 20(10+10)
// 改变$c的值,不会对下面一行语句产生影响
$c = 666; 
// 第二次执行func(),其静态变量$result的值变为 40(20+10+10)
$c = func($a,$b);
echo &#39;<hr />&#39;;
// 这样才是PHP中引用函数的调用方式
$d = &func($a,$b); 
// 第三次执行func(),其静态变量$result的值变为 40(40+10+10)
$d = 888;
// 第四次执行func(),其静态变量$result的值变为 908(888+10+10)
$d = func($a,$b);
?>

Summary: That’s it for this article The entire content of the article is hoped to be helpful to everyone's study.

Related recommendations:

php Implementing custom menus for WeChat development

phpDetailed explanation of two methods of natively exporting excel files

phpMethods to solve DOM garbled characters

The above is the detailed content of Detailed explanation of instances returned by PHP implementation function reference. For more information, please follow other related articles on the PHP Chinese website!

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
How can you check if a PHP session has already started?How can you check if a PHP session has already started?Apr 30, 2025 am 12:20 AM

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Describe a scenario where using sessions is essential in a web application.Describe a scenario where using sessions is essential in a web application.Apr 30, 2025 am 12:16 AM

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

How can you manage concurrent session access in PHP?How can you manage concurrent session access in PHP?Apr 30, 2025 am 12:11 AM

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

What are the limitations of using PHP sessions?What are the limitations of using PHP sessions?Apr 30, 2025 am 12:04 AM

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools