Home  >  Article  >  Backend Development  >  The use of return type declarations in php7 new features

The use of return type declarations in php7 new features

autoload
autoloadOriginal
2021-03-18 10:23:352168browse

Suddenly I feel that php is gradually moving towards a strongly typed language, which is more and more similar to java, c and other strongly typed languages. When using PHP7, you will find that PHP7 contains a new feature, namely return type declaration. A return type declaration specifies the type of value that a function should return. The available types are the same as those available in the parameter declaration.

1. Declarable types:

  • Integer type int

  • Floating point type float

  • Boolean type bool

  • String type string

  • Interface type interfaces

  • Array array

  • Callable

2. Usage example:

<?php
declare(strict_types = 1);
function returnIntValue(int $value): int {
      return $value;
   }
   print(returnIntValue(5));   //输出为5
?>
<?php
//默认declare()处于强制模式下
function returnIntValue(int $value): int {
      return $value+10.5;
   }
   print(returnIntValue(5));   //输出为15 不会报错,声明为int 返回为float
?>

After all, it is still weakly typed language.

<?php
declare(strict_types=1);
function returnIntValue(int $value): int {
      return $value+10.5;
   }
   print(returnIntValue(5));   //会报错,因为在declare()处于严格模式下,声明为int 返回为float,二者类型不符
?>

Recommended: php video tutorial php tutorial

The above is the detailed content of The use of return type declarations in php7 new features. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn