IT박스

PHP 치명적인 오류 : 빈 속성에 액세스 할 수 없습니다.

itboxs 2020. 11. 29. 10:09
반응형

PHP 치명적인 오류 : 빈 속성에 액세스 할 수 없습니다.


나는 처음 php이고 아래 코드를 실행했습니다.

<?php
class my_class{

    var $my_value = array();
    function my_class ($value){
        $this->my_value[] = $value;
    }
    function set_value ($value){
    // Error occurred from here as Undefined variable: my_value
        $this->$my_value = $value;

    }

}

$a = new my_class ('a');
$a->my_value[] = 'b';
$a->set_value ('c');
$a->my_class('d');

foreach ($a->my_value as &$value) {
    echo $value;
}

?>

아래 오류가 있습니다. 오류가 무엇일까요?

Notice: Undefined variable: my_value in C:\xampp\htdocs\MyTestPages\f.php on line 15

Fatal error: Cannot access empty property in C:\xampp\htdocs\MyTestPages\f.php on line 15

잘못된 방법으로 부동산에 액세스합니다. $this->$my_value = ..구문을 사용하여 $ my_value의 값 이름으로 속성을 설정합니다. 당신이 원하는 것은$this->my_value = ..

$var = "my_value";
$this->$var = "test";

와 같다

$this->my_value = "test";

예제에서 몇 가지를 수정하려면 아래 코드가 더 나은 방법입니다.

class my_class {

    public  $my_value = array();

    function __construct ($value) {
        $this->my_value[] = $value;
    }

    function set_value ($value) {
        if (!is_array($value)) {
            throw new Exception("Illegal argument");
        }

        $this->my_value = $value;
    }

    function add_value($value) {
        $this->my_value = $value;
    }
}

$a = new my_class ('a');
$a->my_value[] = 'b';
$a->add_value('c');
$a->set_value(array('d'));

이렇게하면 set_value를 호출 할 때 my_value가 유형을 문자열 또는 다른 것으로 변경하지 않습니다. 그러나 my_value의 값은 공개이므로 여전히 직접 설정할 수 있습니다. 마지막 단계는 my_value를 비공개로 만들고 getter / setter 메서드를 통해서만 my_value에 액세스하는 것입니다.


첫째, var를 사용하여 변수를 선언하지 마십시오.

public $my_value;

그런 다음 다음을 사용하여 액세스 할 수 있습니다.

$this->my_value;

그리고 아닙니다

$this->$my_value;

To access a variable in a class, you must use $this->myVar instead of $this->$myvar.

And, you should use access identifier to declare a variable instead of var.

Please read the doc here.


As I see in your code, it seems you are following an old documentation/tutorial about OOP in PHP based on PHP4 (OOP wasn't supported but adapted somehow to be used in a simple ways), since PHP5 an official support was added and the notation has been changed from what it was.

Please see this code review here:

<?php
class my_class{

    public $my_value = array();

    function __construct( $value ) { // the constructor name is __construct instead of the class name
        $this->my_value[] = $value;
    }
    function set_value ($value){
    // Error occurred from here as Undefined variable: my_value
        $this->my_value = $value; // remove the $ sign
    }

}

$a = new my_class ('a');
$a->my_value[] = 'b';
$a->set_value ('c'); // your array variable here will be replaced by a simple string 
// $a->my_class('d'); // you can call this if you mean calling the contructor 


// at this stage you can't loop on the variable since it have been replaced by a simple string ('c')
foreach ($a->my_value as &$value) { // look for foreach samples to know how to use it well
    echo $value;
}

?>

I hope it helps


Interesting:

  1. You declared an array var $my_value = array();
  2. Pushed value into it $a->my_value[] = 'b';
  3. Assigned a string to variable. (so it is no more array) $a->set_value ('c');
  4. Tried to push a value into array, that does not exist anymore. (it's string) $a->my_class('d');

And your foreach wont work anymore.


This way you can create a new object with a custom property name.

$my_property = 'foo';
$value = 'bar';
$a = (object) array($my_property => $value);

Now you can reach it like:

echo $a->foo;  //returns bar

I realise this answer is not a direct response to the problem described by the OP, but I found this question as a result of searching for the same error message. I thought it worth posting my experience here just in case anybody is muddling over the same thing...

You can encounter the error in question as a result of a poorly formatted for loop over an associative array. In a fit of bone-headedness, I was using -> instead of => in my for statement:

        foreach ($object->someArray as $key->$val) {
            // do something
        }

Of course, I should have had:

        foreach ($object->someArray as $key=>$val) {
            // do something
        }

I confused myself at first, thinking the reported error was referring to the someArray property!

참고URL : https://stackoverflow.com/questions/14920216/php-fatal-error-cannot-access-empty-property

반응형