Home > Backend Development > PHP7 > body text

The use of return type declarations in php7 new features

autoload
Release: 2023-02-17 20:54:01
Original
2226 people have browsed it

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
?>
Copy after login
<?php
//默认declare()处于强制模式下
function returnIntValue(int $value): int {
      return $value+10.5;
   }
   print(returnIntValue(5));   //输出为15 不会报错,声明为int 返回为float
?>
Copy after login

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,二者类型不符
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template