Leggy
Leggy

Reputation: 682

What is the purpose of declaring variables in a class

What is the purpose of declaring a variable at the top of a class if it works without it?

class Testclass
{
    public $testvar = "default value";

    public function setTestvar($testvar) { 
        $this->testvar = $testvar; 
    }

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

compared to:

class Testclass
{
    public function setTestvar($testvar) { 
        $this->testvar = $testvar; 
    }

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

Upvotes: 3

Views: 115

Answers (2)

Hurricane Development
Hurricane Development

Reputation: 2464

In PHP there is no functional purpose to including the declaration. It seems that you have read up on the documentation and you are 100% correct.

There is one case however. If we call the getter before setting the variable, we will get an undefined variable exception.

Now let's think about this.

Let's say I am a programmer, specialized in c++ and java. I'm a pro at those languages (so I pick up PHP pretty quick), and your company just hired me to help work on the web application you are working on. I take a look at this object, and have no clue what's going on.

Really what it comes down to is that PHP is one of the weirdest languages I know. You have stumbled across just one of many odd things that PHP does. This will not be your last. Objects are templates; they are pieces of code that programmers can use for a variety of reasons. The more information and formatting that we can do when making the object, the more effectively it can be used by other programmers. Its the exact same reason as to why we format our code.

TL;DR

No reason, besides documentation, ease of reading, and avoiding Undeclared Variables.

Edit

Another important issue was brought up

Declaring variables in the global context allows you to set your properties visibility. Public or Private. Because you have getters and setters I am assuming that your properties are private. So you need to declare that.

Upvotes: 1

userlond
userlond

Reputation: 3818

Both variants are correct but the second one is lacking when getting testvar before you initialize it.

If you call $test->getTestvar(); before you set it with $test->setTestval('bla bla');, you will get a warning, something like:

Notice: Undefined property: Testclass::$testvar

The second variant also lacks the property visibility part (i.e. private, protected). More about visibility.

The declaration of class properties above methods is a good practice, it's taken from strict oop-languages like java.

Upvotes: 2

Related Questions