Public and private attributes of php classes and objects

Source: Internet
Author: User

This article provides a simple example to illustrate the usage of public and private attributes of php classes and objects. For more information, see.


Private attributes

Attributes that define private attributes can only be used in this class, and can be called through $ this-> in this class. If you reference a private attribute externally, an error is returned.

Instance:

The Code is as follows: Copy code

<? Php
Class People {
Private $ name = "li ming ";
}
$ P = new People ();
Echo $ p-> name;
?>


Note: fields with private attributes cannot be used in subclass.

Public attributes

In php operations, when declaring a field, public, private, protected, final, const, and static are used to describe the scope of the data element of the object. Such characters are called restricted access control characters.

Attributes With the keyword public declaration are called public attributes and can be freely read and modified inside and outside the class. This is obviously not safe enough, undermining the class encapsulation characteristics.

If the field is not declared, the default value is public.

Instance:

The Code is as follows: Copy code

<? Php
Class Man {
Public $ name = "John";/* set public attributes */
Var $ age = 20;
}
$ A = new Man ();
Echo $ a-> name. "<br> ";
Echo $ a-> age;
?>

Change Attribute Value

If the attribute is declared as public, you can change the attribute value or assign the undefined attribute value as needed during external calls.

Instance:

The Code is as follows: Copy code

<? Php
Class Man {
Public $ name = "John ";
Var $ age;
}
$ A = new Man ();
$ A-> name = "Tom";/* change the attribute value */
$ A-> age = 20;/* assign attribute values */
Echo $ a-> name. "<br> ";
Echo $ a-> age;
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.