Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it important to explicitly declare properties in PHP?

Tags:

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;

like image 917
somas1 Avatar asked Sep 16 '09 14:09

somas1


People also ask

What is declaring properties in PHP?

Introduction. Data members declared inside class are called properties. Property is sometimes referred to as attribute or field. In PHP, a property is qualified by one of the access specifier keywords, public, private or protected.

How do you declare and access properties of a class in PHP?

Here, we declare a static property: $value. Then, we echo the value of the static property by using the class name, double colon (::), and the property name (without creating a class first).

How do you declare and access properties of a class?

Note: A property declared without a Visibility modifier will be declared as public . Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property .


1 Answers

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)...

like image 137
nickf Avatar answered Sep 27 '22 18:09

nickf