What is the difference between public, private, and protected?(公共,私有和受保护之间有什么区别?)
问题描述
何时以及为什么应该在类中使用 public
、private
和 protected
函数和变量?它们有什么区别?
When and why should I use public
, private
, and protected
functions and variables inside a class? What is the difference between them?
例子:
// Public
public $variable;
public function doSomething() {
// ...
}
// Private
private $variable;
private function doSomething() {
// ...
}
// Protected
protected $variable;
protected function doSomething() {
// ...
}
推荐答案
你用:
public
范围以使该属性/方法可在任何地方、对象的其他类和实例中使用.
public
scope to make that property/method available from anywhere, other classes and instances of the object.
private
范围,当您希望您的属性/方法仅在其自己的类中可见时.
private
scope when you want your property/method to be visible in its own class only.
protected
范围,当您想让您的属性/方法在所有扩展当前类(包括父类)的类中可见时.
protected
scope when you want to make your property/method visible in all classes that extend current class including the parent class.
如果不使用任何可见性修饰符,则属性/方法将是公共的.
If you don't use any visibility modifier, the property / method will be public.
更多:(获取全面信息)
- PHP 手册 - 可见性
这篇关于公共,私有和受保护之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:公共,私有和受保护之间有什么区别?


基础教程推荐
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01