19th Jan, 2009

How to define and access class variables in PHP

1 Star2 Stars3 Stars4 Stars5 Stars (Nessun voto)
Loading ... Loading ...

One simple thing that I learned in these days at my own expense:
to call a PHP class variable you have to write
$this->foo;
NOT
$this->$foo; (WRONG!)

More precisely, suppose you have a simple PHP class that contains a class variable, $foo in this example:

<?php
   class test {
      public $foo;
 
      public function example() {
         $this->foo = "bar";
      }
   }
 
?>

As you can see from above, to call (or set) the variable $foo in the function example() you need to write:

         $this->foo = "bar";

My error was that I thought you had to write:

         // WRONG! Note the symbol "$" added before the name "foo"!
         $this->$foo = "bar";

Hope this will help someone to avoid my same error.

See also the PHP Manual.

Thanks to Davide.





Leave a response

Your response:

Categories