Home php教程 php手册 php类和对象之公共属性与私有属性

php类和对象之公共属性与私有属性

Jun 13, 2016 am 10:16 AM
php and exist right Attributes article of private Simple

本文章给大家简单的举例说明在php类和对象之公共属性与私有属性用法,有需要了解的朋友可参考。


私有属性

定义了私有属性(private)的属性只能在该类中使用,在该类中可以通过$this->来调用。而在外部引用私有属性将会报错。

实例:

 代码如下 复制代码

 class People{
  private $name="li ming";
 }
 $p=new People();
 echo $p->name;
?>


注意:设置了私有属性的字段也不能在子类中使用。

公共属性

在php类的操作中,声明字段时使用public、private、protected、final、const、static来描述对象的数据元素的作用域,这类字符称为限定访问控制字符。

有关键字public声明的属性称为公共属性,可以自由地在类的内部、外部读取和修改。这样做显然不够安全,破坏了类封装性的特点。

如果字段没有被声明,则默认为public。

实例:

 代码如下 复制代码

 class Man{
  public $name="John"; /* 设定公共属性 */
  var $age=20;
 }
 $a=new Man();
 echo $a->name."
";
 echo $a->age;
?>

改变属性值

如果属性声明为public,则可以在外部调用时根据需要改变属性的值或者赋予未定义的属性值。

实例:

 代码如下 复制代码

 class Man{
  public $name="John"; 
  var $age;
 }
 $a=new Man();
 $a->name="Tom"; /* 改变属性值 */
 $a->age=20; /* 赋予属性值 */
 echo $a->name."
";
 echo $a->age;
?>

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

CakePHP Date and Time

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

CakePHP Project Configuration

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

CakePHP File upload

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

CakePHP Routing

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

Discuss CakePHP

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP Quick Guide

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

How To Set Up Visual Studio Code (VS Code) for PHP Development

See all articles