如果我在php中有一个函数,从解析xml中创建几个对象数组,我如何返回这些数组作为引用?
我需要调用new来分配数组吗?如何在函数中定义它们?
function ParseConfig($rawxml, &$configName, &$radioArr, &$flasherArr, &$irdArr)
对不起,我的意思是返回多个数组作为参数引用。
如何在函数内部创建数组?或者我可以直接把它当作一个数组来使用?
在这种情况下不需要使用引用。PHP使用写时复制机制,该机制还跟踪指向当前值的项的数量。如果从函数返回一个值,并将该结果赋值给一个变量,则refcount
仍然只有1,因为在函数返回时,函数中使用的变量将被销毁。您可以安全地编辑包含函数返回值的变量,而不必担心浪费内存。
function getaz() {
$array = range('a','z');
echo '2: ', memory_get_usage(), "'n";
return $array;
}
echo '1: ', memory_get_usage(), "'n";
$p = getaz();
echo '3: ', memory_get_usage(), "'n";
$p[0] = '3';
echo '4: ', memory_get_usage(), "'n";
$p = array_merge($p, range('A','Z'));
echo '5: ', memory_get_usage();
输出:1: 337304 [initial]
2: 340024 [inside function, value is created]
3: 340072 [outside function, value is assigned]
4: 340072 [element modified but remains same size]
5: 342696 [array extended]
如果我将函数更改为按引用返回,我将得到以下内容:
1: 337312 [it took 8 bytes more memory to define the function]
2: 340032 [accounting for the extra 8 bytes, no change]
3: 340080 [accounting for the extra 8 bytes, no change]
4: 340080 [accounting for the extra 8 bytes, no change]
5: 342704 [accounting for the extra 8 bytes, no change]
希望这对你有帮助!
要了解更多关于如何以及为什么这样工作的信息,请查看这个无耻的博客插件,它解释了PHP如何处理变量和值。
return &$array;
但是只返回$array也可以
我没有注意到你编辑了你的问题,这完全改变了事情。这里有两个不错的选项:
-
在函数的顶部显式地更改它们:
function foo($bar, &$baz, &$qux) { $baz = $qux = array(); }
-
也许这是一个介绍对象的好地方?
class parseConfig { protected $rawXml; protected $configName; protected $radioArr = array(); protected $flasherArr = array(); protected $irdArr = array(); public function __construct($raw_xml = null) { if (!is_null($raw_xml)) { $this->rawXml = $raw_xml; $this->parse(); } } public function parse($raw_xml = null) { if (!is_null($raw_xml)) { $this->rawXml = $raw_xml; } if (empty($this->rawXml)) { return null; } $this->configName = ''; $this->radioArr = $this->flasherArr = $this->irdArr = array(); // parsing happens here, may return false return true; } public function setRawXml($raw_xml) { $this->rawXml = $raw_xml; return $this; } public function getRawXml() { return $this->rawXml; } public function getRadioArr() { return $this->radioArr; } public function getFlasherArr() { return $this->flasherArr; } public function getIrdArr() { return $this->irdArr; } }
任何从函数返回的数组都将通过引用返回,直到您修改该数组,在此之前将生成该数组的副本:
$myArray = functionThatReturnsArray(); //$myArray is a reference to the array returned
echo $myArray[0]; //still a reference
$myArray[0] = 'someNewValue'; //from here $myArray will be a copy of the returned array
你可以在参数列表中指定数组类型(PHP 5.1起),如果你这样做,你可以开始使用它作为一个数组:
function my_function( array &$arr ) {
$arr[0] = 'someValue';
}
如果你不这样做,你应该检查你的函数的顶部:
function my_function( &$arr ) {
if( !is_array($arr) ) $arr = array(); // or generate an error or throw exception
$arr[0] = 'someValue';
}