我很想知道这个问题很长一段时间,PHP如何处理引用是一个好主意使用,我无法解释比使用一个例子更好,让我们看看下面的类然后@的评论setResult方法。
让我们假设我们正在使用模型视图控制器框架,我们正在构建一个基本的AjaxController,到目前为止我们只有1个动作方法(getUsers)。阅读评论,我希望我的问题很清楚,PHP如何处理这些情况,并且我在内存@setResult docblock中写了x次是真的。
class AjaxController{
private $json = array(
'result' => array(),
'errors' => array(),
'debug' => array()
);
/**
* Adds an error, always displayed to users if any errors.
*
* @param type $description
*/
private function addError($description){
$this->json['errors'][] = $description;
}
/**
* Adds an debug message, these are displayed only with DEBUG_MODE.
*
* @param type $description
*/
private function addDebug($description){
$this->json['debug'][] = $description;
}
/**
* QUESTION: How does this go in memory? Cause if I use no references,
* the array would be 3 times in the memory, if the array is big (5000+)
* its pretty much a waste of resources.
*
* 1st time in memory @ model result.
* 2th time in memory @ setResult ($resultSet variable)
* 3th time in memory @ $this->json
*
* @param array $resultSet
*/
private function setResult($resultSet){
$this->json['result'] = $resultSet;
}
/**
* Gets all the users
*/
public function _getUsers(){
$users = new Users();
$this->setResult($users->getUsers());
}
public function __construct(){
if(!DEBUG_MODE && count($this->json['debug']) > 0){
unset($this->json['debug']);
}
if(count($this->json['errors']) > 0){
unset($this->json['errors']);
}
echo json_encode($this->json);
}
}
另一个简单的例子:使用技术A会更好:
function example(){
$latestRequest = $_SESSION['abc']['test']['abc'];
if($latestRequest === null){
$_SESSION['abc']['test']['abc'] = 'test';
}
}
或技术B:
function example(){
$latestRequest =& $_SESSION['abc']['test']['abc'];
if($latestRequest === null){
$latestRequest = 'test';
}
}
感谢您的阅读和建议:)
答案 0 :(得分:2)
简而言之:不要使用参考文献。
写入时的PHP副本。考虑:
$foo = "a large string";
$bar = $foo; // no copy
$zed = $foo; // no copy
$bar .= 'test'; // $foo is duplicated at this point.
// $zed and $foo still point to the same string
只有在需要它们提供的功能时才应使用引用。即,您需要通过对它的引用来修改原始数组或标量。