How to make explicit variable type declaration in PHP?

Asked

Viewed 99 times

0

Taking a course on the Internet, I saw the instructor saying that from PHP 4 (he used 3, so did not test) it was possible to make the explicit declaration of type in object attributes as follows: [escopo] $var:[tipo].

Examples:

class ClassePrincipal{
    // como eu quero realizar as conversões
    private $attr:ClasseSecundaria;
    public  $attr:Carbon;

    // como eu faço atualmente para manter uma tipagem forte
    public function exemplo(Obj1 $o1, string $s, int $i):bool{
        return true;
    }
}

But I find nothing on the subject, nor can I carry out such definitions. I know you can do without, but I like to work with strong typing in other languages, and this functionality caught my attention. Is there a way to accomplish them, in the same way that is done with the functions? Already, thank you.

  • 3

    So use another language, the PHP is gambiarra, is not what you are used to.

  • 2
    1. If you are used to this in other languages, why switch to PHP? PHP was not made to have strong typing. In general, doing so brings more problems than solutions. 2) If the course you are taking used PHP 3, run! We are already in version 7.3 of the language.
  • 1

    If you want to take a look https://wiki.php.net/rfc/typed_properties_v2, but it is very gambiarra, it does not accept void and the classes do not implement a type check mechanism which allows applying an invalid value to a property without error issuance.

  • Augusto, I researched them and tried to apply, but generates the following error: Parse error: syntax error, unexpected 'int' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in /Users/user/Projetos/test/Classe.php on line 3, Do you know if I’m doing something wrong? Thank you (code below).

  • <?php&#xA; class ClasseTipada{&#xA; public int $var1;&#xA; }&#xA;?>

  • <?php&#xA; require_once 'ClasseTipada.php';&#xA; $classe = new ClasseTipada();&#xA; $classe->var1 = 2;&#xA; $classe->var1 = 'soap';&#xA;?>

  • 1

    Declare properties without type as "typed" properties (quotation marks as fake typing) are only supported in language version 7.4.

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.