Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Scalar Type in PHP7

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 330
    Comment on it

    In PHP files we have weak type-checked content (Weak type-checked means no way to check the variable is of what type). Now, in PHP7 we can check what type variable we are using in our code by using SCALAR TYPE.

    Declare scalar type in the starting of the file with the value of 1, then php file code is strong type-checked.  strict_types declaration should be the first statement of the php file otherwise it will give compile time error.

     

    HOW TO DECLARE:

    declare(strict_types = 1);

    strict_types can have value either 1 or 0. No other value can be used for declaration.

    If 1, strict type checking mode will work of function call and return statement in the file and if 0, weak type checking mode will work.

     

    WEAK TYPE CHECKED:

    function sum(int $a, int $b) {
        return $a + $b;
    }
    var_dump(sum(10,20));
    var_dump(sum("10","20"));

    OUTPUT OF THE ABOVE CODE IS:

    int(3)
    int(3)

     

    STRICT TYPE CHECKED:

    declare(strict_types = 1);
    
     function sum(int $a, int $b) {
        return $a + $b;
    }
    var_dump(sum(1,2));
    var_dump(sum("1","2"));

    OUTPUT OF THE ABOVE CODE IS:

    int(3)
    <br />
    <b>Fatal error</b>:  Uncaught TypeError: Argument 1 passed to add() must be of the type integer, string given, called in [...][...] on line 8 and defined in [...][...]:4
    Stack trace:
    #0 [...][...](8): add('1', '2')
    #1 {main}
      thrown in <b>[...][...]</b> on line <b>4</b><br />

     

    When one declare "strict_types" then only TYPE ERROR we get as it is checking for the type. The error is occurring because we are using string in the add function calling and in definition we are passing int parameters.

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: