Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Fatal error: Cannot access empty property

I'm new to php and I have executed below code.

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

I got below errors. What could be the error?

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 
like image 798
Bishan Avatar asked Feb 17 '13 10:02

Bishan


2 Answers

You access the property in the wrong way. With the $this->$my_value = .. syntax, you set the property with the name of the value in $my_value. What you want is $this->my_value = ..

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

is the same as

$this->my_value = "test"; 

To fix a few things from your example, the code below is a better aproach

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

This ensures, that my_value won't change it's type to string or something else when you call set_value. But you can still set the value of my_value direct, because it's public. The final step is, to make my_value private and only access my_value over getter/setter methods

like image 180
Philipp Avatar answered Sep 18 '22 11:09

Philipp


First, don't declare variables using var, but

public $my_value; 

Then you can access it using

$this->my_value; 

and not

$this->$my_value; 
like image 27
Marko D Avatar answered Sep 19 '22 11:09

Marko D