PHP 7 Scalar Types Declarations

PHP 7 Scalar Types Declarations

Learn what are Scalar Types, why do we need them and how to use new things like: String, Int, Float and Bool in all new PHP7. The PHP is no longer limited to custom objects, arrays and mixed variable typing anymore.

Scalar Types – explanation

Scalar Types are also called: Type Declarations, this includes: bool, float, int and string have been added to the already existing argument types like: Class/interface name, self or array. These scalar types are added to function definitions by prefixing an argument with such type, for instance:

function myFunction(string $name, bool $flag) { .. }

 

Scalar Types – usage

If we would pass at least one incorrect argument type to the function with predefined typed arguments, then we will get a Fatal Error thrown with the appropriate message.

myFunction('some_name', 20)

Will result in:

Fatal error: Uncaught TypeError: Argument 2 passed to myFunction() must be an instance of boolean, integer given, called in - on line 1 and defined in -:1
Bear in mind that boolean and integer won’t be treated as supported scalar types as they are classes, not types to use in declarations. An alternative for comparing these will be a usage of: instanceof().

 

All possible new usages of new types:

//arguments
function myFunction(string $name, bool $flag, int $number, float $price) { .. }

//variable definitions
string $name = 'john';
bool $flag = true;
int $number = 2;
float $price 2.94;

 

Reference

PHP 7 News & Updates v7.0 – 7.4 Book https://www.amazon.com/PHP-News-Updates-v7-0-7-4/dp/1727202481/

Rate this artcile
[Total: 1 Average: 5]