9

property_write_visibility

 3 years ago
source link: https://wiki.php.net/rfc/property_write_visibility
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Introduction

With the introduction of typed properties in PHP 7.4, properties have become far more powerful. However there are still common scenarios where you'll need to use magic methods or methods for properties in order to deal with disconnected write/set vs read/get visibility for properties, like readonly, writeonly or immutable like semantic. This requires unnecessary boilerplate, makes usage less ergonomic and in the case of magic methods hurts performance.

This RFC resolves this issue by proposing to allow classes to optionally declare property write/set visibility, disconnected from read/get visibility.

Under this RFC, code like the following using magic methods:

/**
 * @property-read int $id
 * @property-read string $name
 */
class User {
    private int $id;
    protected string $name;
 
    public function __construct(int $id, string $name) {
        $this->id = $id;
        $this->name = $name;
    }
 
    public function __get($property)
    {
        if (property_exists($this, $property)) {
            // We return value here as non public properties are "readonly" in this class
            return $this->$property;
        }
        throw new PropertyNotFoundException($property, static::class);
    }
 
    public function __set($property, $value)
    {
        if (property_exists($this, $property)) {
            // Here private/protected property is attempted accessed outside allowed scope, so we throw
            throw new PropertyReadOnlyException($property, static::class);
        }
        throw new PropertyNotFoundException($property, static::class);
    }
 
    public function __isset($property)
    {
        return property_exists($this, $property);
    }
 
    public function __unset($property)
    {
        $this->__set($property, null);
    }
}

might be written as (Language syntax Option A):

class User {
    public:private int $id;
    public:protected string $name;
 
    public function __construct(int $id, string $name) {
        $this->id = $id;
        $this->name = $name;
    }
}

or (Language Syntax Option B):

class User {
    public private(set) int $id;
    public protected(set) string $name;
 
    public function __construct(int $id, string $name) {
        $this->id = $id;
        $this->name = $name;
    }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK