PHP 按引用返回


简介

在 PHP中,还可以让一个函数返回引用。这可用于查找引用应绑定到哪个变量。要定义一个返回引用的函数,请在它的名称之前加上&符号。

示例

在以下示例中,将 myfunction() 定义为按引用返回。其中包含一个静态变量,其引用将被返回并分配给一个全局变量。局部静态变量的值也会改变,它的引用将在外部被分配为不同的值。

示例

 演示

<?php
function &myfunction(){
   static $x=10;
   echo "x Inside function: ",$x,"
";    return $x; } $a=&myfunction(); //contains reference to 4x in function echo "returned by reference: ", $a, "
"; $a=$a+10; //increments variable inside function too $a=&myfunction(); ?>

输出

此示例给出了以下输出

x Inside function: 10
returned by reference: 10
x Inside function: 20

返回引用的方法

类也可以有一个能够返回引用的方法。这样可以从类的外部更改私有实例变量的值

示例

 演示

<?php
class myclass{
   private $val;
   function __construct($x){
      $this->val=$x;
   }
   function &getbyref(){
      return $this->val;
   }
   function getbyval(){
      return $this->val;
   }
}
$a=new myclass(10);
$b=&$a->getbyref();
$b=100;
echo "Value of private property: ", $a->getbyval();
?>

输出

上述脚本的结果如下

Value of private property: 100

更新时间:2020-9 月 18 日

870 次浏览

提升您的职业生涯

完成课程后获得认证

开始
广告
© . All rights reserved.