Piklu Guha
Piklu Guha

Reputation: 577

Declaring php class member variables

I was trying to write a class in such simple way

class piklu
{
   private $x=5;
   public function display()
   {
      echo $this->$x;
   }
}

but when after creating object of this class I'm calling the function display it is displaying an error unkown variable $x. Can any body suggest me what exactly I have to do to declare a private member variable in php.

Upvotes: 4

Views: 10940

Answers (2)

Ruwantha
Ruwantha

Reputation: 2653

You have done a silght mistake on calling variable. You can call the class member variable by

$this->x

Upvotes: 6

Jonah Bishop
Jonah Bishop

Reputation: 12581

Your echo statement is incorrect, which is your problem. It should be:

public function display()
{
    echo $this->x;
}

Note that there's only one $ here: right before the keyword this. You mistakenly had two dollar signs.

Upvotes: 8

Related Questions