在PHP 5中,您是否需要使用&修饰符通过引用传递?例如,
class People() { }
$p = new People();
function one($a) { $a = null; }
function two(&$a) { $a = null; )
Run Code Online (Sandbox Code Playgroud)
在PHP4中,您需要&修改器在进行更改后维护引用,但是我对我读过的关于PHP5自动使用pass-by-reference的主题感到困惑,除非明确克隆对象.
在PHP5中,是否 & 需要通过引用传递所有类型的对象(变量,类,数组......)?
在这段代码中:
<?php
class Foo
{
var $value;
function foo($value)
{
$this->setValue($value);
}
function setValue($value)
{
$this->value=$value;
}
}
class Bar
{
var $foos=array();
function Bar()
{
for ($x=1; $x<=10; $x++)
{
$this->foos[$x]=new Foo("Foo # $x");
}
}
function getFoo($index)
{
return $this->foos[$index];
}
function test()
{
$testFoo=$this->getFoo(5);
$testFoo->setValue("My value has now changed");
}
}
?>
Run Code Online (Sandbox Code Playgroud)
当该方法Bar::test()运行并且它改变了foo对象数组中foo#5的值时,数组中的实际foo#5是否会受到影响,或者该$testFoo变量只是一个最终不再存在的局部变量功能?
我已经注意到PHP中单例的奇怪行为,没有更好的方法来解释这个但是举个例子.
假设我有以下单例类:
class Singleton
{
protected function __construct()
{
// Deny direct instantion!
}
protected function __clone()
{
// Deny cloning!
}
public static function &Instance()
{
static $Instance;
echo 'Class Echo'.PHP_EOL;
var_dump($Instance);
if (!isset($Instance)) {
$Instance = new self;
}
return $Instance;
}
}
Run Code Online (Sandbox Code Playgroud)
并具有以下功能:
function Test($Init = FALSE)
{
static $Instance;
if ($Init === TRUE && !isset($Instance)) {
$Instance =& Singleton::Instance();
}
echo 'Function Echo'.PHP_EOL;
var_dump($Instance);
return $Instance;
}
Run Code Online (Sandbox Code Playgroud)
当我使用以下内容时:
Test(TRUE);
Test();
Singleton::Instance();
Run Code Online (Sandbox Code Playgroud)
输出是:
Class Echo
NULL
Function …Run Code Online (Sandbox Code Playgroud)