Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Not getting it? Reply To: Not getting it?

#183401
__
Participant

I see that here and there within tutorials but I also see it omitted. When should I set this and when can I leave it out?

As a rule, you should always define the properties your class uses. This makes it easier to plan/organize your code, and lets you recall at a glance what it does.

This also goes back to your public/private question (though if you’re still concentrating on other things feel free to ignore this part for now; read it when you’re ready):

If you just assign a property (like $this->name = $name; in your constructor), it will be “public.” There’s not much effective difference in declaring the property beforehand, in the class definition, but it does make plain that the property exists and can be relied upon.

“Public” means that the property can be accessed/assigned/changed from anywhere. So, this sort of thing can happen:

$dog = new animal( 'dog' );
$dog->name = 'raccoon';

$dog->name();
// prints "raccoon"

If you want to make sure this cannot happen, you can make the property private:

class animal {

        private $name;

        public function __construct($name) {
           $this->name = $name;
        }

        public function name() {
            return $this->name;
        }
    }

Then:

$dog = new animal( 'dog' );

$dog->name = "raccoon";
// fatal error: Cannot access private property animal::$name …

$dog->name();
// prints 'dog'