Guest User

Tipagem de funções em PHP (retornos)

a guest
May 1st, 2020
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.55 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * "?string" indica que a função pode retornar um valor "null" ou uma "string"
  5. */
  6. function retorno($var): ?string
  7. {
  8. return $var;
  9. }
  10.  
  11. /**
  12. * Caso remova "?" de function retorno($var): string o erro abaixo será gerado
  13. * Uncaught TypeError: Return value of retorno() must be of the type string, null returned in
  14. */
  15. echo retorno(null);
  16.  
  17. /**
  18. * Aqui será retornado "Boi" como uma string
  19. */
  20. echo retorno("Boi");
  21.  
  22. /**
  23. * Sim, uma "string" (que não esteja vazia) é diferente de um valor "null"
  24. */
  25. var_dump("Boi" <> null);
Advertisement
Add Comment
Please, Sign In to add comment