
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
PHP 7 - Scalar Type Declarations
In PHP 7, a new feature, Scalar type declarations, has been introduced. Scalar type declaration has two options −
coercive − coercive is default mode and need not to be specified.
strict − strict mode has to explicitly hinted.
Following types for function parameters can be enforced using the above modes −
- int
- float
- bool
- string
- interfaces
- array
- callable
Example - Coercive Mode
<?php // Coercive mode function sum(int ...$ints) { return array_sum($ints); } print(sum(2, '3', 4.1)); ?>
It produces the following browser output −
9
Example - Strict Mode
<?php // Strict mode declare(strict_types = 1); function sum(int ...$ints) { return array_sum($ints); } print(sum(2, '3', 4.1)); ?>
It produces the following browser output −
Fatal error: Uncaught TypeError: Argument 2 passed to sum() must be of the type integer, string given, ...
Advertisements