Description
php version: 8.4.2
If it is possible to operate on non-public member properties of a class, it does not matter whether the member properties that are applied final have the final keyword or not.
class Example
{
final protected mixed $value = 0;
}
$obj = new Example;
var_dump(
(function () {
$this->value += 1;
return $this->value;
})->call($obj)
);
// Output:
// int(1)
By promoting the scope, it is also possible to achieve the same behavior as a final method by accessing the attributes of the class.
class Database {
private PDO $connection;
final public function connect($host, $username, $password) {
$this->connect = new PDO(... func_num_args());
}
}
$db = new Database;
$db->connect('mysql:host=localhost;dbname=old_database;charset=utf8', 'username', 'password');
// change database
(function () {
$pdo = new PDO('mysql:host=localhost;dbname=new_database;charset=utf8', 'username', 'password');
$this->connection = $pdo;
})->call($db)
Some built-in extensions require final classes to not allow inheritance, but they cannot avoid providing scopes to operate on internal members of the class.