faqts : Computers : Programming : Languages : PHP : kms : Classes

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

12 of 28 people (43%) answered Yes
Recently 6 of 10 people (60%) answered Yes

Entry

Are PHP Class variable declarations necessary?

Apr 22nd, 2002 13:12
Rick Overman,


Is it necessay to use VAR to declare class variables?

It seems like class variables can be added dynamically at any time,
but I have yet to find documentation that says this this legal.
I would hate to write a bunch of code to take advantage of this
"feature" only to find out it was a bug and fixed in the next release 
of PHP.


EXAMPLE:

class foo
{
   var $a;              // <<< variable 'a' declared
   function foo()
   {
      $this->a = "test";
   }
};

class foo2
{
   function foo2()
   {
      $this->a = "test";  // assignment to undeclared class variable 'a'
   }
};


$foo_with    = new foo();     
$foo_without = new foo2();

echo "<pre>" .var_dump($foo_with). "</pre>";
echo "<pre>" .var_dump($foo_without). "</pre>";

OUTPUT:
object(foo)(1) { ["a"]=> string(4) "test" } 

object(foo2)(1) { ["a"]=> string(4) "test" } 



This also seems to work:

$foo_without->b = "yet another";

echo "<pre>" .var_dump($foo_without) . "</pre>";

OUTPUT:
object(foo2)(2) { ["a"]=> string(4) "test" ["b"]=> string(11) "yet 
another" }