开发者

Why do I get a syntax error when I don't declare a member variable as public or private? [closed]

开发者 https://www.devze.com 2023-03-23 12:21 出处:网络
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time,or an extraordinarily narrow situation that is not generally applic
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 10 years ago.

I get a syntax error when I don't declare a member variable as public or private. However if I don't declare a member function as public or private, it defaults to public.

// Class
class Building {
    // Object variables/properties
    private $number_of_floors = 5; // These buildings have 5 floors
    private $color;

    // Class constructor
    public function __construct($paint) {
        $this->color = $paint;
    }

    public function describe() {
        printf('This building has %d floors. It is %s in color.', 
            $this->number_of_floors, 
            $this->color
        );
    }
}

For the above code, try deleting "private" from the member variables and it won't run, but if you delete 开发者_StackOverflow中文版"public" from the member functions it will run.


From The PHP online manual:

"Class properties must be defined as public, private, or protected."

...and...

"Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public."

[Emphasis mine]

I'm not sure why this is, but it's just the way the language is specified.


You need a keyword before member variables. That keyword used to be var:

class Foo {

    var $bar = null;

    function baz() { }

}

var is to properties as function is to methods.

var is deprecated though in favor of explicit visibility declarations. So public, protected, private is to properties as function is to methods now. Methods additionally take a visibility declaration as well.

Logically they could have chosen public var $bar as the syntax for properties, but went with a simple public $bar instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消