Why is type hinting necessary in PHP?

前端 未结 6 1661
北恋
北恋 2020-12-05 07:27

I am having trouble wrapping my head around the importance of Type hinting in PHP.

Apparently \'type hinting\' in PHP can be defined as follows:

6条回答
  •  盖世英雄少女心
    2020-12-05 07:45

    Type hinting is a natural process. At first it may seem like extra work but it is very helpful as your project grows in PHP. It allows for better readability and makes error control and strict programming conventions easier to apply.

    Initially, you must implement the ‘contract’, where the contract is a php interface which can ‘lock’ constants and the key public methods and their arguments, as such:

    interface SongInterface {
        //...
    }
    
    class Song implements SongInterface
    {
        public $title;
        public $lyrics;
        //...
    }
    

    Then continue with the actual execution part:

    $song = (object) new Song;
    
    $song->title = (string) "Beat it!";
    $song->lyrics = (string) "It doesn't matter who's wrong or right... just beat it!";
    
    
    function sing(SongInterface $song): string
    {
        $html = (string)  "Singing the song called " . $song->title
        . "

    " . $song->lyrics . "

    "; return htmlentities($html, ENT_QUOTES, 'utf-8'); } echo sing($song);

    Using an interface, you only define the functions and then implement it in a song class. This way you can always inject another song class (with newer functionalities and changes) without breaking your application. Check out oop interfaces: http://php.net/manual/en/language.oop5.interfaces.php

    Since php7, you can also define the return type of a function. https://wiki.php.net/rfc/return_types

提交回复
热议问题