Skip to content

8.4: property hooks #1142

Open
Open
@genintho

Description

@genintho
  • get - simple
    public string $email {
       get => 'mailto:' . $this->email;
    }
  • get - block
       get {
           'mailto:' . $this->email;
        }
  • set - full block form
set ($value) { $this->[propertyName = $value }
  • block form with implicit $value
set { $this->[propertyName = $value }
  • expression form with explicit $value
set ($value) => {expression}
  • expression form with implicit $value
set => {expression}// expression form with implicit $value
  • get by reference
&get => { }
  • default value
public string $role = 'anonymous' {
    set {
        Roles::from($value);
        $this->role = $value;
    }
}
  • final on hooks
class StandardUser
{
    public string $email {
        final set {
           if (! filter_var($value, FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE)) {
               throw new InvalidArgumentException('Invalid email');
           }
           $this->email = $value;
        }
    }
}
  • final on property
class User 
{
    // Child classes may not add hooks of any kind to this property.
    public final string $name;
 
    // Child classes may not add any hooks or override set,
    // but this set will still apply.
    public final string $username {
        set => [strtolower](http://www.php.net/strtolower)($value);
    }
}
  • abstract
abstract class StandardUser
{
    abstract public string $email { get; }
}
  • interface - get
interface I
{
    // An implementing class MUST have a publicly-readable property,
    // but whether or not it's publicly settable is unrestricted.
    public string $readable { get; }
}
  • interface - set
interface I
{ 
    // An implementing class MUST have a publicly-writeable property,
    // but whether or not it's publicly readable is unrestricted.
    public string $writeable { set; }
}
  • interface - get + set
interface I
{
    // An implementing class MUST have a property that is both publicly
    // readable and publicly writeable.
    public string $both { get; set; }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions