Skip to content
Katie Volz edited this page Jun 9, 2020 · 3 revisions

Class Properties is a PHP library which uses PHP Attributes (polyfilled by Virtual Attributes for PHP 7) to provide C#-like property support in PHP. Instead of:

class MyClass
{
    private string $myStr;
    public function __construct(string $myStr)
    {
        $this->myStr = $myStr;
    }
    public function __get(string $propertyName)
    {
        switch($propertyName)
        {
            case "myStr":
                return $this->myStr;
            default:
                return null;
        }
    }
}

You can write:

class MyClass
{
    public function __construct(
        <<ReadOnlyProperty>> private string $myStr
    ){}
}

Or, in PHP 7, using the VirtualAttributes polyfill:

class MyClass
{
    // <<ReadOnlyProperty>>
    private string $myStr;
    public function __construct(string $myStr)
    {
        $this->myStr = $myStr;
    }
}
(new ReadOnlyProperty)->addToProperty(MyClass::class, "myStr");
Clone this wiki locally