(PHP 8 >= 8.6.0)
ReflectionProperty::isReadable — Checks whether a property can be read from a given scope
Checks whether reading the property from the given
scope would be allowed.
The visibility of the property, its
hooks,
the __get() and
__isset() magic methods and,
if an object is given, the state of the property
on that object are taken into account.
Nota:
A return value of
truedoes not guarantee that reading the property succeeds. For example, agethook or __get() may still throw an exception.
scope
The name of the class from which the property would be read,
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 read. If null, only the
declaration of the property is considered.
Must be null for static properties.
Returns false if the property is not visible from
scope, if it is a
virtual property
without a get hook, or if it is uninitialized.
Otherwise true is returned.
However, if the class defines __get(),
true is returned for a non-static property that is not visible from
scope or does not exist on
object.
If object is given and the class also defines
__isset(), the result of calling
__isset() is returned instead.
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.
Ejemplo #1 ReflectionProperty::isReadable() example
<?php
class User
{
public string $name;
private string $password = 'secret';
}
$user = new User();
$nameProperty = new ReflectionProperty(User::class, 'name');
// Without an object, only the declaration of the property is considered
var_dump($nameProperty->isReadable(null));
// The property is not initialized yet
var_dump($nameProperty->isReadable(null, $user));
$user->name = 'Alice';
var_dump($nameProperty->isReadable(null, $user));
$passwordProperty = new ReflectionProperty(User::class, 'password');
// Private properties can only be read from inside the class
var_dump($passwordProperty->isReadable(null));
var_dump($passwordProperty->isReadable(User::class));El ejemplo anterior mostrará:
bool(true) bool(false) bool(true) bool(false) bool(true)
Nota:
If
objectis an uninitialized lazy object, calling this method may trigger its initialization.