1

我已经通过在函数定义和变量赋值中都放置与号来阅读 PHP 中返回引用的部分。但是,我还没有在与面向对象编程无关的 php 代码中找到“返回引用”的示例。任何人都可以为此提供用途和示例吗?

4

2 回答 2

2

让我从一个非常简单的例子开始,

class Test {

    //Public intentionally
    //Because we are going to access it directly later
    //in order to see if it's changed
    public $property = 'test';

    /**
     * Look carefully at getPropReference() title
     * we have an ampersand there, that is we're indicating
     * that we're returning a reference to the class property
     * 
     * @return string A reference to $property
     */
    public function &getPropReference()
    {
         return $this->property;
    }
}


$test = new Test();

//IMPORTANT!! Assign to $_foo a reference, not a copy!
//Otherwise, it does not make sense at all
$_foo =& $test->getPropReference();

//Now when you change a $_foo the property of an $test object would be changed as well
$_foo = "another string";

// As you can see the public property of the class
// has been changed as well
var_dump($test->property); // Outputs: string(14) "another string" 

$_foo = "yet another string";
var_dump($test->property);   //Outputs "yet another string"
于 2012-12-31T23:30:07.037 回答
-1

更新:这个答案涉及通过引用传递,而不是通过引用返回。保留它的信息价值。

读这个:

http://php.net/manual/en/language.references.pass.php

然后看看这个例子:

<?php
function AddTimestamp(&$mytimes)
{
    $mytimes[] = time();
}


$times = array();
AddTimestamp($times);
AddTimestamp($times);
AddTimestamp($times);

// Result is an array with 3 timestamps.

这可以使用面向对象的技术更好地实现吗?也许,但有时需要/理由来修改现有的基于值的数据结构或变量。

考虑一下:

function ValidateString(&$input, &$ErrorList)
{
   $input = trim($input);
   if(strlen($input) < 1 || strlen($input) > 10) 
   {
      $ErrorList[] = 'Input must be between 1 and 10 characters.';
      return False;
   }
} 

$Err = array();
$Name = '  Jason    ';

ValidateString($Name, $Err);

// At this point, $Name is trimmed. If there was an error, $Err has the message.

因此,根据您的需要,仍有时间在 PHP 中通过引用传递。对象总是通过引用传递的,所以无论何时你将数据封装在一个对象中,它都会自动成为一个引用。

于 2012-12-31T22:17:14.837 回答