PHP-Types and Type Checking

 Types and Type Checking

  • Dynamic Type Checking
    • Static : All data types are defined before running the program
    • Dynamic : Allows assignment of values at runtime
  • Type juggling and type casting
    • Type juggling : automatic PHP rules
    • Type casting : how different types are converted into each othe
Important Note: 

  • Static type checking results in a compilation error - or detected when the program is actually run - Dynamic type checking, runtime error. If no error checking is not implemented, then the string may be converted to a numeric value with unexpected results.
  • PHP Non-explicit type : Example if you assign a string value to a variable
    $var()
    ,
    $var()
      becomes a string. If you then assign an integer value to  
    $var()
     , It becomes an integer.
  • An example of PHP's automatic type conversion is the addition operation '+'. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. This does NOT change the type of the operands themselves; the only change is in how the operands are evaluated.
  • If you wish to force a variable to be evaluated as a certain type, the name of the desired type is written in parentheses before the variable which is to be cast (this may be too advanced)
        The casts allowed here

(int), (integer) - cast to integer

(bool), (boolean) - cast to boolean

(float), (double), (real) - cast to float

(string) - cast to string

(array) - cast to array

(object) - cast to object

(unset) - cast to NULL


  • Example How to cast
<?php
$varA = 5; // is an integer
$varB = (bool) $varA; // is a boolean
$varC = "$varA" // is a string ?>

Post a Comment

Previous Post Next Post