Development Tip

엄격한 표준 : 변수 만 참조로 전달해야합니다.

yourdevel 2020. 10. 5. 21:00
반응형

엄격한 표준 : 변수 만 참조로 전달해야합니다.


$el = array_shift($instance->find(..))

위의 코드는 어떻게 든 엄격한 표준 경고를보고하지만 다음과 같은 것은 아닙니다.

function get_arr(){
    return array(1,2);
}
$el = array_shift(get_arr());

어쨌든 언제 경고를보고할까요?


다음 코드를 고려하십시오.

error_reporting(E_STRICT);
class test {
    function test_arr(&$a) {
        var_dump($a);   
    }
    function get_arr() {
        return array(1,2);  
    }
}

$t= new test;
$t->test_arr($t->get_arr());

그러면 다음과 같은 출력이 생성됩니다.

Strict Standards: Only variables should be passed by reference in `test.php` on line 14
array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}

이유? test::get_arr()메서드는 변수가 아니며 엄격 모드에서는 경고가 생성됩니다. get_arr()메서드 배열 값을 반환 하므로이 동작은 매우 직관적이지 않습니다 .

엄격 모드에서이 오류를 해결하려면 메서드의 서명을 변경하여 참조를 사용하지 않도록합니다.

function test_arr($a) {
    var_dump($a);  
}

서명을 변경할 수 없으므로 array_shift중간 변수를 사용할 수도 있습니다.

$inter= get_arr();
$el= array_shift($inter);

$instance->find() 변수에 대한 참조를 반환합니다.

이 참조를 변수에 먼저 저장하지 않고 함수에 대한 인수로 사용하려고 할 때 보고서를 얻습니다.

이것은 메모리 누수를 방지하는 데 도움이되며 아마도 다음 PHP 버전에서 오류가 될 것입니다.

두 번째 코드는 다음과 같이 작성하면 오류가 발생합니다 (& in 함수 서명).

function &get_arr(){
    return array(1,2);
}
$el = array_shift(get_arr());

따라서 빠른 (그다지 좋지 않은) 수정은 다음과 같습니다.

$el = array_shift($tmp = $instance->find(..));

기본적으로 임시 변수에 대한 할당을 먼저 수행하고 변수를 인수로 보냅니다.


오류의 원인은 내부 PHP 프로그래밍 데이터 구조 함수 인 array_shift () [php.net/end]를 사용하기 때문입니다.

이 함수는 배열을 매개 변수로 사용합니다. array_shift()매뉴얼 의 프로토 타입에 앰퍼샌드가 표시되어 있지만 해당 기능의 확장 된 정의 뒤에는주의 문서가 없으며 매개 변수가 실제로 참조로 전달되었다는 명백한 설명도 없습니다.

Perhaps this is /understood/. I did not understand, however, so it was difficult for me to detect the cause of the error.

Reproduce code:

function get_arr()
{
 return array(1,2);
}
$array = get_arr();
$el = array_shift($array);

The second snippet doesn't work either and that's why. array_shift is a modifier function, that changes its argument, therefore it expects its parameter to be a reference, and you cannot reference something that is not a variable. See Rasmus' explanations here: Strict standards: Only variables should be passed by reference


This code:

$monthly_index = array_shift(unpack('H*', date('m/Y')));

Need to be changed into:

$date_time = date('m/Y');
$unpack = unpack('H*', $date_time);
array_shift($unpack);

Well, in obvious cases like that, you can always tell PHP to suppress messages by using "@" in front of the function.

$monthly_index = @array_shift(unpack('H*', date('m/Y')));

It may not be one of the best programming practices to suppress all errors this way, but in certain cases (like this one) it comes handy and is acceptable.

As result, I am sure your friend SysAdmin will be pleased with a less polluted error.log

참고URL : https://stackoverflow.com/questions/2354609/strict-standards-only-variables-should-be-passed-by-reference

반응형