php class attributes

伊谢尔伦
Release: 2016-11-23 14:22:54
Original
1594 people have browsed it

The variable members of a class are called "properties", or "fields" or "features". They are collectively called "properties" in this document. A property declaration starts with the keywords public, protected or private, and is followed by an ordinary variable declaration. Variables in attributes can be initialized, but the initialized value must be a constant. The constant here means that the PHP script can obtain its value during the compilation phase and does not rely on runtime information to evaluate.

Note:

In order to be backward compatible with PHP 4, PHP 5 declared properties can still use the keyword var directly instead of (or appended to) public, protected or private. But var is no longer needed. In PHP 5.0 to 5.1.3, var will be considered deprecated and an E_STRICT warning will be thrown, but after 5.1.3 it will no longer be considered deprecated and no warning will be thrown.

If you declare a property directly using var without using one of public, protected or private, PHP 5 will treat it as public.

In the member method of the class, you can use -> (object operator): $this->property (where property is the name of the property) to access non-static properties. Static properties are accessed using :: (double colon): self::$property.

Example #1 Property declaration

class SimpleClass

{

//Wrong property declaration

public $var1 = 'hello '.'world';

public $var2 = <<

hello world

EOD;

public $var3 = 1+2;

public $var4 = self::myStaticMethod();

public $var5 = $myVar;


//Correct attribute declaration

public $var6 = myConstant;

public $var7 = array(true,false);

//PHP5.3.0 and later, the following statement is also correct

public $var8 = <<< 'EOD'

hello world

EOD;

}

Unlike heredocs, nowdocs can be used in any static data context, including property declarations.

Example #2 Example: Use nowdoc to initialize properties

//PHP5.3.0 onwards

public $var = <<<'EOD'

hello world

EOD;

Note:

Nowdoc support It was added in PHP 5.3.0.


Related labels:
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