简体   繁体   中英

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; 
    }
}

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:

: Undefined property: Testclass::$testvar :未定义的属性:Testclass :: $ testvar

The second variant also lacks the property visibility part (ie 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM