2014-11-24 1 views
0

ArrayAccess PHP 인터페이스에 대한 지난 질문을 많이 읽었으며 참조를 반환 할 수있는 방법은 offsetGet입니다. 이 클래스는 array 변수를 래핑하는 간단한 클래스를 구현했습니다. offsetGet 메서드는 참조를 반환하지만 Only variable references should be returned by reference이라는 오류가 발생합니다. 왜?PHP ArrayAccess - 참조가있는 다차원 배열 및 offsetGet

class My_Class implements ArrayAccess { 
    private $data = array(); 

    ... 

    public function &offsetGet($offset) { 
     return isset($this->data[ $offset ]) ? $this->data[ $offset ] : null; 
    } 

    ... 
} 
나는이 클래스와 다차원 배열을 사용할 수 있도록하고 싶습니다

:

$myclass = new My_Class(); 

$myclass['test'] = array(); 
$myclass['test']['test2'] = array(); 
$myclass['test']['test2'][] = 'my string'; 
+0

변수에 언 바운드 된'NULL '을 반환하기 때문에, 변수를'if (! thiset> data [$ offset]) $ this-> data [$ offset] = null; return $ this-> data [$ offset];'?/테스트하기에는 너무 느림 – Wrikken

+0

함수가 참조가 아닌 표현식의 결과를 반환하고 '& null'참조를 사용할 수 없습니다. 임시 변수를 사용해보십시오 – mario

답변

0

난 당신이 표현이 아닌 변수의 결과를 반환하는 becuase이라고 생각합니다. if 문을 작성하고 실제 변수를 반환하십시오.

메소드 '& offsetGet'는 변수에 대한 참조 (포인터)를 반환 php manual -> second note

0

참조.

메서드 서명을 '& offsetGet'에서 'offsetGet'으로 수정하거나 변수를 사용하여 반환 값을 보유해야합니다. 이 코드

// modify method signiture 
public function offsetGet($offset) { 
    return isset($this->data[ $offset ]) ? $this->data[ $offset ] : null; 
} 

// or use a variable to hold the return value. 
public function &offsetGet($offset) { 
    $returnValue = isset($this->data[ $offset ]) ? $this->data[ $offset ] : null; 
    return $returnValue; 
} 
+0

두 번째 문은 새로운 오류를 던지고있다 : My_Class의 오버로드 된 요소의 간접 수정이 아무런 영향을 미치지 않는다. – Stefano

+0

문맥을 스택 위로 가져라. offsetGet? –

+0

문제가 있습니다. 새 클래스 인스턴스를 만들고 배열에 일부 데이터를 설정하려고합니다. – Stefano

0

:

public function &offsetGet($offset) { 
    $returnValue = isset($this->data[ $offset ]) ? $this->data[ $offset ] : null; 
    return $returnValue; 
} 

$returnValue$this->data[$offset]의 복사본이 아닌 기준이다.

당신은 자신에게 참조를 확인해야하고, 그것을 위해 당신은 if 문으로 삼항 연산자를 교체해야 :

public function &offsetGet($offset) { 
    if (isset($this->data[$offset]) { 
     $returnValue &= $this->data[$offset]; // note the &= 
    } 
    else { 
     $returnValue = null; 
    } 
    return $returnValue; 
} 

트릭을해야한다.

존재하지 않는 경우, 배열의 존재하지 않는 키를 묻는 질문과 같이 Exception을 던지기를 원합니다. 당신이 반환 값이 참조되지 않습니다 때문에 ,

$myclass['non-existing']['test2'] = array(); 

아마도 indirect overloaded modification 오류가 발생합니다 때문에 금지되어야한다.