Loading...

PHP 7: Scalar Type Declarations - New Feature!

PHP 7: Scalar Type Declarations - New Feature!
Scalar Type Declarations

Watch my video on Scalar Variables: https://www.youtube.com/watch?v=6V6R8H1_FX4&t=65s

My video on return type declarations: https://youtu.be/hbgxgXWdYmk

1. Introduced in php 5.6 as type hints and having undergone some changes, in PHP 7 they are now declarations
- Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.
2. Types of Scalar: INT, FLOAT, STRING, BOOL
 - Aliases for the above scalar types are not supported. So use bool, not boolean, or you'll have an error or it'll be treated as an instance of the Boolean class.
 - If you want more information on Scalar variables, check out my video What are Scalar Variables?
3. PHP has weak typing. By default PHP will coerce scalar values from one type to another
 - if it can't, IE: bool but expecting array, a TypeError will be thrown
4. Strict typing can be turned on, on a file by file basis
 - the exception to this is that an integer can be passed to a declaration expecting a float
 - To enable strict mode, the declare statement is used with the strict_types declaration:
 - turning on strict mode enables it for return type declartions as well
 - Strict typing applies to function calls made from within the file with strict typing enabled, not to the functions declared within that file. If a file without strict typing enabled makes a call to a function that was defined in a file with strict typing, the caller's preference (weak typing) will be respected, and the value will be coerced.

More Info on Scalar Type Declarations: https://secure.php.net/manual/en/migration70.new-features.php#migration70.new-features.scalar-type-declarations

RRelated Posts

Should You Learn PHP? - Pros and Cons

Most web developers either love or hate PHP. In this video we will go over some of the advantages and disadvantages of learning PHP compared to other server side languages SUGGESTED: PHP Front To

New features in PHP 7: a quick overview

PHP 7 has finally been released. It's a mile stone release that offers a lot of new features such as: * Scalar type hints * Return type declarations * Anonymous classes * The Closure::call()

CComments

  • hicham choukradi
    thank you for this video