Home  >  Article  >  Backend Development  >  New features of php7: scalar type declaration

New features of php7: scalar type declaration

autoload
autoloadOriginal
2021-03-18 09:50:142428browse

PHP7 has added the feature of scalar type declaration. There are two modes for scalar type declaration:

  • Forced mode (default)

  • strict Model

1. Syntax format:

declare( strict_types=1 );//代码中通过制定 strict_types 的值( 1 或者 0 )
  • # 1 means strict type verification mode , applied to function calls and return statements;

  • 0 indicates weak type checking mode.

2. Usage

Use

declare(strict_types=1) to set whether to enable strict matching mode. After it is enabled , if the parameter passed in is not a preset parameter type, an error will be reported, for example:

<?php
declare(strict_types=1);
function test(int $param) {
	var_dump($param);
}
test("1");//会提示报错

Use

declare(strict_types=0) to set whether to enable the forced mode. After it is enabled, if If the parameter entered is not a preset parameter type, no error will be reported, for example:

<?php
declare(strict_types=1);
function test(int $param) {
	var_dump($param);
}
test("1");//不会提示报错

Tips: In forced mode, it will be judged whether the currently passed in parameter is the set parameter type. If not, Then forced conversion will be performed. If the forced conversion cannot be performed, of course an error will be reported. Generally, forced conversion between scalar types can be passed.

3. Available types

  • int

  • float

  • bool

  • string

  • ##nterfaces
  • ##array
  • callable
  • Recommended:
  • php video tutorial

php tutorial

The above is the detailed content of New features of php7: scalar type declaration. 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