2012-02-13 3 views
0

나는이 질문을 오랫동안 궁금해합니다. PHP에서 참조를 처리하는 것이 좋은 생각이며 사용법을 설명하는 것보다 더 잘 설명 할 수 없으므로 다음 클래스를 살펴보고 @ setResult 메소드의 주석.PHP 메모리 참조

우리는 모델 뷰 컨트롤러 프레임 워크를 사용하고 있고 기본 AjaxController를 구축하고 있다고 상상해보십시오. 지금까지는 하나의 액션 메소드 (getUsers) 만있었습니다. 의견을 읽고, 내 질문에 분명히 희망, PHP는 이런 종류의 상황을 처리하고 메모리에 x 번에 대해 쓴 x 사실 setResult docblock.

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'; 
    } 
} 

읽어 주셔서 감사하고 조언 :

+1

참고 문헌에 대한 PHP 매뉴얼 페이지 : [http://php.net/manual/en/language.references.php](http://php://php.net/manual/en/language.references.php) – bfavaretto

답변

2

에서 짧은 : 참조를 사용하지 마십시오.

PHP copy on write. 고려하십시오 :

$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 

제공하는 기능이 필요할 때만 참조를 사용해야합니다. 즉, 원본 배열이나 스칼라에 대한 참조를 통해 수정해야합니다.

+0

감사합니다. 당신의 대답은, 나는 이제 그것을 이해합니다. 방금 다른 예제를 추가했습니다.이 기술을 사용하면 어떤 기법을 사용하는 것이 더 나을지 조언 해 주시면 정말 대단합니다. 다시 한번 감사합니다 :) – randomKek

+0

@MikeVercoelen, 원래 데이터를 업데이트하는 기능이 필요하기 때문에 참조 된 항목을 설정 한 두 번째 예제는 적절한 참조입니다. 그것은 눈에 띄는 방식으로 일들을 빠르게 할 것이 아니기 때문에 그것을 사용하지 마십시오. 또한 참조를 마쳤 으면 실수로 나중에 다시 사용하지 않도록 'unset()'해야합니다. 그리고이 예제는 고안된 것이지만, 일반적으로 더 좋은 해결책은 그러한 복잡한 배열을 모두 피하는 것입니다. 일반적으로 객체가 더 적합하다는 것을 의미하므로 ref가 필요하지 않습니다. – Matthew

+0

복잡한 배열이 적절한 상황에 처한 경우 복사/붙여 넣기 오류를 제거하기 때문에 예제와 같이 참조를 사용하는 경향이 있습니다. 그러나이 부분의 대답은 기본적으로 사람들이 동의하지 않는 의견입니다. – Matthew