类的变量成员叫做 属性,或者叫 字段,在本文档统一称为 属性 。从 PHP 7.4 开始,属性声明是由关键字
public
,protected
或者
private
开头,然后是类型声明,然后跟一个普通的变量声明来组成。属性中的变量可以初始化,但是初始化的值必须是 常数 。
有关 public
,protected
和 private
的更多详细信息,请查看访问控制(可见性)。
注意:
另一种不推荐的声明类属性的方法是使用
var
关键字,因为它是为了向后兼容 PHP 4。 如果使用,会将其视为public
。
在类的成员方法里面,可以用 ->
(对象运算符):$this->property(其中
property
是该属性名)这种方式来访问非静态属性。静态属性则是用
::
(双冒号):self::$property
来访问。更多静态属性与非静态属性的区别参见 Static 关键字。
当一个方法在类定义内部被调用时,有一个可用的伪变量 $this。$this 是一个到主叫对象的引用(通常是该方法所从属的对象,但如果是从第二个对象静态调用时也可能是另一个对象)。
示例 #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(true, false);
public $var8 = <<<'EOD'
hello world
EOD;
}
?>
注意:
更多关于类/对象的处理函数,请查看类/对象函数。
从 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(1234, null);
var_dump($user->id);
var_dump($user->name);
?>
以上例程会输出:
int(1234) NULL
类型属性必须在访问前初始化,否则会抛出 Error 。
示例 #3 访问属性
<?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());
?>
以上例程会输出:
string(8) "triangle" int(3) string(6) "circle" Fatal error: Uncaught Error: Typed property Shape::$numberOfSides must not be accessed before initialization
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->i += 1;
$test->i++;
++$test->i;
$test->ary[] = 1;
$test->ary[0][] = 1;
$ref =& $test->i;
$test->i =& $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;
?>