Tutorial on protected and const attribute _ php for PHP classes and objects

Source: Internet
Author: User
The protected and const attributes of php classes and objects. This article introduces the use of protected and const attributes of classes and objects in php. For more information, see. The field defined by the const attribute in the const attribute is a constant. This article introduces the use of the protected and const attributes of classes and objects in php. For more information, see.

Const attributes
The field defined with the const attribute is a constant. constants in the class are similar to static variables. The difference is that the value of a constant cannot be changed once it is assigned a value.

The const definition constant does not require the $ symbol. its structure is as follows:

Const constant name // constant name cannot use the $ symbol

Instance:

The code is as follows:

Class Date {
Const M = "Monday ";
}
Echo "today is". Date: M;
?>


Tip: The constant names defined by const are generally capitalized. this is a convention. we need to develop a good naming convention. If the defined constant is composed of multiple words, the underscore _ link is used, which is also a convention. For example, FILE_SIZE.

Protected attributes

The field scope defined by protected is between public and private. if this member is declared as protected (protected), it means that this field can only be used in this class and its subclass.

Instance:

The code is as follows:

Class me {
Protected $ Money = 100;
Protected $ price1 = 60;

Public function compute ($ price ){
If ($ this-> price1 <= $ price ){
Echo "Okay, I sold it to you.
";
$ This-> Money = $ this-> Money + $ price;
Return "I have a total of". $ this-> Money. "RMB ";
}
Else {
Echo "I don't sell it, $ price is too cheap.
";
Return "now I am still". $ this-> Money. "RMB ";
}
}
}

$ Now = new me;
Echo $ now-> timeout (30 );
?>

Bytes. The field defined by the const attribute in the const attribute is a constant, class...

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.