Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

php - 公共,私有和受保护的有什么区别?(What is the difference between public, private, and protected?)

When and why should I use public , private , and protected functions and variables inside a class?

(什么时候以及为什么应该在类内使用publicprivateprotected函数和变量?)

What is the difference between them?

(它们之间有什么区别?)

Examples:

(例子:)

// Public
public $variable;
public function doSomething() {
  // ...
}

// Private
private $variable;
private function doSomething() {
  // ...
}

// Protected
protected $variable;
protected function doSomething() {
  // ...
}
  ask by Adam translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You use:

(你用:)

  • public scope to make that property/method available from anywhere, other classes and instances of the object.

    (public范围,以使该属性/方法可从任何位置,对象的其他类和实例使用。)

  • private scope when you want your property/method to be visible in its own class only.

    (当您只希望您的属性/方法仅在其自己的类中可见时,请使用private范围。)

  • protected scope when you want to make your property/method visible in all classes that extend current class including the parent class.

    (当您想使您的属性/方法在扩展当前类的所有类(包括父类)中可见时,请使用protected范围。)

More: (For comprehensive information)

(更多:(有关全面信息))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...