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.
So use another language, the PHP is gambiarra, is not what you are used to.
– Maniero
– Woss
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 Vasques
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).– Arthur Siqueira
<?php
 class ClasseTipada{
 public int $var1;
 }
?>
– Arthur Siqueira
<?php
 require_once 'ClasseTipada.php';
 $classe = new ClasseTipada();
 $classe->var1 = 2;
 $classe->var1 = 'soap';
?>
– Arthur Siqueira
Declare properties without type as "typed" properties (quotation marks as fake typing) are only supported in language version 7.4.
– Augusto Vasques