PHP allows to dynamically set and get class properties that are not declared in the class. Since PHP 8.2, dynamic properties are deprecated.
Let's say we have User class which do not have any declared properties:
User.php
<?php
class User {}
Since PHP 8.2, the following code emits a deprecation warning because the id property is set dynamically:
main.php
<?php
require_once 'User.php';
$user = new User();
$user->id = 1;
echo $user->id;
Deprecated: Creation of dynamic property User::$id is deprecated in main.php on line 6
1
The class can be rewritten using encapsulation principle. We declare getId and setId methods to get and set property.
User.php
<?php
class User
{
private int $id;
public function getId(): int { return $this->id; }
public function setId(int $id): void { $this->id = $id; }
}
main.php
<?php
require_once 'User.php';
$user = new User();
$user->setId(1);
echo $user->getId();
The stdClass class
Dynamic properties on objects of stdClass class is not deprecated. The following example does not emit a deprecation warning:
<?php
$obj = new stdClass();
$obj->id = 1;
echo $obj->id;
The __get and __set magic methods
Dynamic properties deprecation warning is not emitted for classes that declare __set magic method. The following example does not emit a deprecation warning because User class declares __set magic method:
User.php
<?php
class User
{
private array $attributes = [];
public function __set(string $name, mixed $value): void
{
$this->attributes[$name] = $value;
}
public function __get(string $name): mixed
{
return $this->attributes[$name] ?? null;
}
}
main.php
<?php
require_once 'User.php';
$user = new User();
$user->id = 1;
echo $user->id;
Leave a Comment
Cancel reply