Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why declare class' properties when constructor initialize this properties

Tags:

oop

php

Write what is best and why?

class Chat
{
    private $_couleur;
    private $_race;

    function __construct($couleur, $race)
    {
        $this->_couleur = $couleur;
        $this->_race = "$race";
    }

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

Or

class Chat
{
    function __construct($couleur, $race)
    {
        $this->_couleur = $couleur;
        $this->_race = "$race";
    }

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

Because $this->_couleur is initialized when the class is instancied, so declare the property directly in the class is useless, isn't ?

like image 742
JohnnyC Avatar asked Jan 07 '23 14:01

JohnnyC


1 Answers

Declaring the variables at the top of your class is a very good practice, because it makes it clear to anyone that reads your code which properties the class has private and which properties the class has public.

In the second example your variables will be public because they're dynamically generated.

When your constructor would be much bigger it is a pain in the ass as developer to find out where your variables are introduced.
It is also good to set default values (if they are always the same) to the variables in the class as opposed to the constructor. It makes your code more readable and understandable.

like image 115
Bas van Stein Avatar answered Jan 16 '23 21:01

Bas van Stein