屬性

類的變量成員叫做屬性,或者叫字段,在本文檔統(tǒng)一稱為屬性。 屬性開頭至少使用一個(gè)修飾符(比如 訪問(wèn)控制(可見性)靜態(tài)(static)關(guān)鍵字, 或者自 PHP 8.1.0 起支持的 readonly), 除了 readonly 屬性之外都是可選的,然后自 PHP 7.4 起可以跟一個(gè)類型聲明,然后跟一個(gè)普通的變量聲明來(lái)組成。屬性中的變量可以初始化,但是初始化的值必須是 常量值。

注意:

另一種過(guò)時(shí)的聲明類屬性的方法是使用 var 關(guān)鍵字,而不是使用修飾符。

注意: 沒有聲明 訪問(wèn)控制(可見性) 修飾符的屬性將默認(rèn)聲明為 public

在類的成員方法里面,可以用 ->(對(duì)象運(yùn)算符):$this->property(其中 property 是該屬性名)這種方式來(lái)訪問(wèn)非靜態(tài)屬性。靜態(tài)屬性則是用 ::(雙冒號(hào)):self::$property 來(lái)訪問(wèn)。更多靜態(tài)屬性與非靜態(tài)屬性的區(qū)別參見 靜態(tài)(static)關(guān)鍵字。

當(dāng)一個(gè)方法在類定義內(nèi)部被調(diào)用時(shí),有一個(gè)可用的偽變量 $this。$this 是一個(gè)到主叫對(duì)象的引用(通常是該方法所從屬的對(duì)象,但如果是從第二個(gè)對(duì)象靜態(tài)調(diào)用時(shí)也可能是另一個(gè)對(duì)象)。

示例 #1 屬性聲明

<?php
class SimpleClass
{
   public 
$var1 'hello ' 'world';
   public 
$var2 = <<<EOD
hello world
EOD;
   public 
$var3 1+2;
   
// 正確的屬性聲明
   
public $var4 self::myStaticMethod();
   public 
$var5 $myVar;

   
// 正確的屬性聲明
   
public $var6 myConstant;
   public 
$var7 = array(truefalse);

   public 
$var8 = <<<'EOD'
hello world
EOD;

   
// 沒有訪問(wèn)控制修飾符:
   
static $var9;
   
readonly int $var10;
}
?>

注意:

更多關(guān)于類/對(duì)象的處理函數(shù),請(qǐng)查看類/對(duì)象函數(shù)。

類型聲明

從 PHP 7.4.0 開始,屬性定義可以包含 類型聲明 , 但 callable 除外。

示例 #2 類型聲明的示例

<?php

class User
{
    public 
int $id;
    public ?
string $name;

    public function 
__construct(int $id, ?string $name)
    {
        
$this->id $id;
        
$this->name $name;
    }
}

$user = new User(1234null);

var_dump($user->id);
var_dump($user->name);

?>

以上例程會(huì)輸出:

int(1234)
NULL

類型屬性必須在訪問(wèn)前初始化,否則會(huì)拋出 Error 。

示例 #3 訪問(wèn)屬性

<?php

class Shape
{
    public 
int $numberOfSides;
    public 
string $name;

    public function 
setNumberOfSides(int $numberOfSides): void
    
{
        
$this->numberOfSides $numberOfSides;
    }

    public function 
setName(string $name): void
    
{
        
$this->name $name;
    }

    public function 
getNumberOfSides(): int
    
{
        return 
$this->numberOfSides;
    }

    public function 
getName(): string
    
{
        return 
$this->name;
    }
}

$triangle = new Shape();
$triangle->setName("triangle");
$triangle->setNumberofSides(3);
var_dump($triangle->getName());
var_dump($triangle->getNumberOfSides());

$circle = new Shape();
$circle->setName("circle");
var_dump($circle->getName());
var_dump($circle->getNumberOfSides());
?>

以上例程會(huì)輸出:

string(8) "triangle"
int(3)
string(6) "circle"

Fatal error: Uncaught Error: Typed property Shape::$numberOfSides must not be accessed before initialization

Readonly properties

As of PHP 8.1.0, a property can be declared with the readonly modifier, which prevents modification of the property after initialization.

示例 #4 Example of readonly properties

<?php
class Test {
   public 
readonly string $prop;
   public function 
__construct(string $prop) {
       
// Legal initialization.
       
$this->prop $prop;
   }
}
$test = new Test("foobar");
// Legal read.
var_dump($test->prop); // string(6) "foobar"
// Illegal reassignment. It does not matter that the assigned value is the same.
$test->prop "foobar";
// Error: Cannot modify readonly property Test::$prop
?>

注意:

The readonly modifier can only be applied to typed properties. A readonly property without type constraints can be created using the mixed type.

注意:

Readonly static properties are not supported.

A readonly property can only be initialized once, and only from the scope where it has been declared. Any other assignment or modification of the property will result in an Error exception.

示例 #5 Illegal initialization of readonly properties

<?php
class Test1 {
    public 
readonly string $prop;
}
$test1 = new Test1;
// Illegal initialization outside of private scope.
$test1->prop "foobar";
// Error: Cannot initialize readonly property Test1::$prop from global scope
?>

注意:

Specifying an explicit default value on readonly properties is not allowed, because a readonly property with a default value is essentially the same as a constant, and thus not particularly useful.

<?php
class Test {
    
// Fatal error: Readonly property Test::$prop cannot have default value
    
public readonly int $prop 42;
}
?>

注意:

Readonly properties cannot be unset() once they are initialized. However, it is possible to unset a readonly property prior to initialization, from the scope where the property has been declared.

Modifications are not necessarily plain assignments, all of the following will also result in an Error exception:

<?php
class Test {
    public function 
__construct(
        public 
readonly int $i 0,
        public 
readonly array $ary = [],
    ) {}
}
$test = new Test;
$test->+= 1;
$test->i++;
++
$test->i;
$test->ary[] = 1;
$test->ary[0][] = 1;
$ref =& $test->i;
$test->=& $ref;
byRef($test->i);
foreach (
$test as &$prop);
?>

However, readonly properties do not preclude interior mutability. Objects (or resources) stored in readonly properties may still be modified internally:

<?php
class Test {
    public function 
__construct(public readonly object $obj) {}
}
$test = new Test(new stdClass);
// Legal interior mutation.
$test->obj->foo 1;
// Illegal reassignment.
$test->obj = new stdClass;
?>