OO PHP basic get and set methods "Undefined variable"

I've read about OO PHP programming and encapsulation and I am still a little confused.

I have this code:

class Item {

    private $id;
    private $description;

    public function __construct($id) {
        $this->id = $id;
    }

    public function getDescription() {
        return $this->$description;
    }

    public function setDescription($description) {
        $this->description = $description;
    }

}

      

In my testclass.php file, when I use a set and get a description of such functions:

$item = new Item(1234);
$item->setDescription("Test description");
echo $item->getDescription();

      

I am getting the error Undefined variable: description. Can anyone explain to me why this is, because I thought the point of a method set is to define a variable? I thought you were declaring a variable in a class and then you are defining the variable when you use the set method so that the get method can be accessed?

+3


source to share


2 answers


Just want to add to @prisoner's correct answer.

$this->description

      

does not match

$this->$description

      

because that's what you would call "variable variable".

For example:



$this->description = "THIS IS A DESCRIPTION!"
$any_variable_name = "description";

echo $this->$any_variable_name; // will echo "THIS IS A DESCRIPTION"
echo $this->description // will echo "THIS IS A DESCRIPTION"
echo $this->$description // will result in an "undefined error" since $description is undefined.

      

See http://php.net/manual/en/language.variables.variable.php for details .

A useful example would be if you want to access a variable / function in a given structure.

Example:

$url = parseUrl() // returns 'user'

$this->user = 'jim';

$arr = array('jim' => 'the good man', 'bart' => 'the bad man');

echo $arr[$this->$url] // returns 'the good man'

      

+2


source


return $this->$description;

      



wrong. You are referring to a variable $description

, not a return $this->description

. Read variable variables.

+4


source







All Articles