Type declarations
As of PHP 7.4.0, property definitions can include
Type declarations,
with the exception of callable.
Example #2 Example of typed properties
<?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);
?>
The above example will output:
Typed properties must be initialized before accessing, otherwise an
Error is thrown.
Example #3 Accessing properties
<?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());
?>
The above example will output:
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. Prior to PHP 8.4.0
a readonly property is implicitly private-set, and may only be written to
from the same class. As of PHP 8.4.0, readonly properties are implicitly
protected(set),
so may be set from child classes. That may be overridden
explicitly if desired.
Example #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
?>
Note:
The readonly modifier can only be applied to typed properties.
A readonly property without type constraints can be created using the Mixed type.
Note:
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.
Example #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
?>
Note:
Readonly properties can only be initialized by a direct assignment.
An uninitialized readonly property cannot be initialized by reference, not even
from the scope where it has been declared: passing it to a function parameter that
expects to be passed by reference, or assigning it by reference, results in an
Error exception.
As of PHP 8.6.0, a readonly property may declare a default value.
The default value counts as the initialization of the property,
so the property cannot be assigned again, not even from the constructor.
This makes it possible to implement a get-only
interface property
with a fixed value, without having to assign it in a constructor.
Prior to PHP 8.6.0, declaring a default value on a readonly property
resulted in a compile-time error.
Note:
A default value on a
promoted constructor parameter
is the default value of the parameter, not of the property.
Note:
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.
A readonly property with a default value is initialized when the object is created, and can therefore never be unset.
Modifications are not necessarily plain assignments, all of the following will also result in an Error exception:
However, readonly properties do not preclude interior mutability. Objects (or resources) stored in readonly properties may still be modified internally:
As of PHP 8.3.0, readonly properties can be reinitialized when cloning an object
using the __clone() method.
Example #6 Readonly properties and cloning
<?php
class Test1 {
public readonly ?string $prop;
public function __clone() {
$this->prop = null;
}
public function setProp(string $prop): void {
$this->prop = $prop;
}
}
$test1 = new Test1;
$test1->setProp('foobar');
$test2 = clone $test1;
var_dump($test2->prop); // NULL
?>
Note:
As of PHP 8.4.0, indirect modification of a readonly property within
__clone(), such as acquiring a
reference to it ($ref = &$this->prop), is no longer
allowed. This was already forbidden during readonly initialization.
Dynamic properties
If trying to assign to a non-existent property on an object,
PHP will automatically create a corresponding property.
This dynamically created property will only be
available on this class instance.
Dynamic properties are supported by stdClass and its subclasses. Other classes may enable similar behavior with AllowDynamicProperties or property overloading.
Warning
Creating a dynamic property is deprecated as of PHP 8.2.0,
unless the class is marked with the
#[\AllowDynamicProperties] attribute.
It is recommended to declare the property instead.
To handle arbitrary property names, the class should implement the magic
methods __get() and
__set().
Marking the class with the attribute remains an option, but is
generally considered a last resort.