(PHP 8 >= 8.6.0)
ReflectionProperty::isWritable — Checks whether a property can be written from a given scope
Checks whether writing to the property from the given
scope would be allowed.
The visibility of the property, including its
asymmetric visibility,
its hooks,
the __set() magic method and,
if an object is given, the state of a
readonly property
on that object are taken into account.
Зауваження:
A return value of
truedoes not guarantee that writing to the property succeeds. For example, asethook or __set() may still throw an exception, and the type of the assigned value is not considered.
scope
The name of the class from which the property would be written,
or null for the global scope, that is, code outside of any class.
Use static::class to check from the scope of the
calling code, if inside a class.
object
The object on which the property would be written. If null, only the
declaration of the property is considered.
Must be null for static properties.
Returns false if the visibility or
set visibility
of the property does not allow writing from
scope, if it is a
virtual property
without a set hook, or if
object is given and the readonly property is
already initialized on it.
Otherwise true is returned.
However, if the class defines __set(),
true is returned for a non-static property that is not visible from
scope.
Throws a ReflectionException if
object is given for a static property, or if
object is not an instance of the class the property
was declared in.
Throws an Error if scope is
not the name of an existing class.
Приклад #1 ReflectionProperty::isWritable() example
<?php
class User
{
public readonly string $name;
public function setName(string $name): void
{
$this->name = $name;
}
}
$reflectionProperty = new ReflectionProperty(User::class, 'name');
$user = new User();
// Readonly properties can only be written from inside the class
var_dump($reflectionProperty->isWritable(null, $user));
// The property is not initialized yet
var_dump($reflectionProperty->isWritable(User::class, $user));
$user->setName('Alice');
var_dump($reflectionProperty->isWritable(User::class, $user));
// Without an object, only the declaration of the property is considered
var_dump($reflectionProperty->isWritable(User::class));Поданий вище приклад виведе:
bool(false) bool(true) bool(false) bool(true)
Зауваження:
If
objectis an uninitialized lazy object, calling this method on a readonly property may trigger its initialization.