Asked  1 Year ago    Answers:  5   Viewed   10 times

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

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

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


I got below errors. What could be the error?

Notice: Undefined variable: my_value in C:xampphtdocsMyTestPagesf.php on line 15

Fatal error: Cannot access empty property in C:xampphtdocsMyTestPagesf.php on line 15



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

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

Wednesday, June 9, 2021

The PHPUnit documentation says used to say to include/require PHPUnit/Framework.php, as follows:

require_once ('PHPUnit/Framework/TestCase.php');


As of PHPUnit 3.5, there is a built-in autoloader class that will handle this for you:

require_once 'PHPUnit/Autoload.php';

Thanks to Phoenix for pointing this out!

Thursday, April 1, 2021

The answer was due to hidden characters located in the lessons.db file.

The error shown had nothing to do with this and I would like to thank everyone who took the time to give their two pence.

Thursday, April 1, 2021

You are trying to pass a pointer to your array in array_push. That is why the fatal error is encountered. Simply use:

array_push( $image_set, $images[fname] );

Note: array_push() will raise a warning if the first argument is not an array.

Saturday, August 14, 2021

You appear to have an error on line 21. Change:




For reference, this is is known as a variable variable. Example:

$a = 'b';
$b = 'I am a variable variable';
echo $$a; // equivalent to `echo $b;` prints 'I am a variable variable'
Monday, October 11, 2021
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :