0

I have just started practicing OO programming using PHP. Recently I have encountered a problem.

I am trying to declare a variable inside a class, but leaving it uninitialized. Later inside a method of the class when I try to initialize the variable it shows the following errors:

Undefined variable: a in C:\wamp\www\sample.php on line 6

Fatal error: Cannot access empty property in C:\wamp\www\sample.php on line 6

Here is the code that I am trying to execute:

<?php
    class Sample{
        public $a;

        function call($b){
            $this->$a = $b;
            echo $a;
        }
    }

    $sam = new Sample();
    $sam->call(5);
?>

How do I fix this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Asutosh Rana
  • 64
  • 1
  • 11
  • Possible duplicate of [PHP Fatal error: Cannot access empty property](http://stackoverflow.com/questions/14920216/php-fatal-error-cannot-access-empty-property) – Ken Y-N Oct 14 '16 at 07:57

2 Answers2

1

In the function call, $a does not exist. Only $this->a (without $ before the a), which is the property of your "sam" object, and $b, which is an input parameter. Plus when you set the property, you must not use $a. Use $this->a.

If you would have a variable which contains a property name of the class, you should use $this->$a, which would mean $this->asdf, if $a = 'asdf';

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
OlajosCs
  • 231
  • 2
  • 9
1

The correct syntax is $this->a, not $this->$a.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dimlucas
  • 5,040
  • 7
  • 37
  • 54