我已经通过在函数定义和变量赋值中放入&符号来阅读PHP中返回引用的部分。但是,我还没有在php代码中找到与面向对象编程无关的“返回引用”的示例。任何人都可以提供此用途和示例吗?
答案 0 :(得分: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"
答案 1 :(得分:-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引用。对象总是通过引用传递,因此无论何时将数据封装在对象中,它都会自动成为引用。