PHP 8.5.13 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.

参见

+添加备注

用户贡献的备注

此页面尚无用户贡献的备注。
To Top