PKJ.no

Petter Kjelkenes, a blog about technical stuff.

PHP 7.4, typed properties RFC

Posted on 19. September, 2018

There is an ongoing vote process for typed properties. Typed properties would be really good for PHP, as PHP has already gone on the way to be a strict types language.

Edit:

The RFC has been accepted, and PHP 7.4 will now include typed properties.

The benefits of the new typed properties:

  • Relying on dockblocks for code completion in IDE's.
  • Runtime errors if wrong types are used.
  • Future performance improvements can be done internally in PHP.
  • Less type checking code, meaning cleaner code.

This is an example of how you can define typed properties, in reference to the RFC:

Less code

First of, the obvious. There are no longer needs for types in dockblocks and getters / setters to ensure type safety. This alone is a huge deal. Today, per property there are at least 21 lines of code that can be removed. This given the PSR coding standards.

<?php

class Example {
  /**
   * @var string
   */
  private $title;
  
  /**
   * @var string $title
   */
  public function setTitle(string $title)
  {
      $this->title = $title;
  }
  
  /**
   * @return string
   */
  public function getTitle()
  {
      return $this->title;
  }
}

Which can be converted to 3 lines of code.

<?php

class Example {
  public string $title;
}

Sometimes you would need a getter / setter in cases where the contents of the variable mutates to something else. Still the dockblock would not be needed.

Comments

Hello

My name is Petter Kjelkenes. I live in a small country named Norway.

I am a full-stack developer, mostly using tech like: PHP, Symfony, Node.js, React and CMS tech like eZ Platform + sanity.

Contact me

Petter Kjelkenes

(+47) 482 913 65