Home > Backend Development > PHP Tutorial > Public properties and private properties of PHP classes and objects_PHP tutorial

Public properties and private properties of PHP classes and objects_PHP tutorial

WBOY
Release: 2016-07-13 17:15:25
Original
1500 people have browsed it

This article gives you a simple example of the usage of public attributes and private attributes in PHP classes and objects. Friends who need to know more can refer to it.


Private attribute

Properties that define private attributes can only be used in this class, and can be called through $this-> in this class. However, referencing private properties externally will result in an error.

Example:

Example:
The code is as follows
 代码如下 复制代码

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

Copy code


class People{ private $name="li ming"; }

$p=new People();

echo $p->name; ?>

Note: Fields with private properties cannot be used in subclasses.
 代码如下 复制代码

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

Public properties

In PHP class operations, when declaring fields, use public, private, protected, final, const, and static to describe the scope of the object's data elements. These characters are called limited access control characters.

Attributes declared with the keyword public are called public attributes and can be read and modified freely inside and outside the class. This is obviously not safe enough and destroys the encapsulation characteristics of the class.

 代码如下 复制代码

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

If the field is not declared, it defaults to public.
The code is as follows Copy code

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template