PHP 8.6.0 Released!

ReflectionProperty::isWritable

(PHP 8 >= 8.6.0)

ReflectionProperty::isWritable — Checks whether a property can be written from a given scope

説明

public function ReflectionProperty::isWritable(?string $scope, ?object $object = null): bool

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 true does not guarantee that writing to the property succeeds. For example, a set hook 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 object is an uninitialized lazy object, calling this method on a readonly property may trigger its initialization.

参考

+add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top