Php – Is it important to explicitly declare properties in PHP

PHP

I have followed a tutorial to create a simple blog writing application in PHP and have modified the classes in this tutorial so that they have additional capabilities. Modifying this very bare bones app has given me a better understanding of how PHP works, however I have run across an interesting situation.

One of the classes in my project has about a half dozen class properties such as public $id, public $author, public $post. These properties are declared at the beginning of this class however I find that if I remove all but one of these properties the app still functions correctly.

Is it wrong to remove a property declaration such as public $datePosted from the beginning of a class if this class still assigns variables to this property like this: $this->datePosted = $someVariableName;

Best Answer

If you try to access a class property which hasn't been declared, PHP will issue a notice:

class Foo { }

var $fu = new Foo();
echo $fu->baz;

Notice: Undefined property: Foo::$baz in blah.php on line 4

If you set a value first ($fu->baz = 'blah') then it won't complain, but that's not a great situation.

You should definitely declare all your class variables (unless of course you want to have some fun with the magic methods)...