Php class attribute and class constant declaration assignment

Source: Internet
Author: User
Tags parse error
The variable members of a class are called "attributes", "fields", and "features". in this document, they are collectively referred to as "attributes ". Attribute declaration starts with the keyword public, protected, or private, and then starts with a variable. The variables in the attribute can be initialized. today, when a constant of a class is declared and assigned a value, an error is made.

Example:


define('ONE', '111'); class test{const TWO = ONE . '222'; public $ab = ONE . '222'; function pp(){echo self::TWO;}}

The above statement is actually not feasible in syntax, and the browser will report an error:



Parse error: syntax error, unexpected '.'

I checked the php manual and explained how to assign values to class attributes and class constants:

Explanation of class attributes:
The variable members of a class are called "attributes", "fields", and "features". in this document, they are collectively referred to as "attributes ". Attribute declaration starts with the keyword public, protected, or private, and then starts with a variable. The variables in the property can be initialized, but the initialization value must be a constant. the constant here means that the php script is a constant during compilation, instead of the constant calculated in the running phase after the compilation phase.

Explanation of class constants:



The constant value must be a fixed value and cannot be a variable, class attribute, or result of other operations (such as function call.

We can see that the class attribute and class constant values must be fixed values during initialization, that is, they cannot be values after processing.

Example of declaring class attributes in the php manual:
 

In fact, if you really need to obtain the processed result when assigning values to class variables, you can put it in the constructor for processing.

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.