📚

Types and Typecasting in PHP

Jul 17, 2024

Types and Typecasting in PHP

Introduction

  • PHP is dynamically typed (weakly typed), meaning variable types are not defined explicitly and can change during runtime.
  • Dynamic typing implies type checking at runtime, as opposed to compile-time in statically typed languages (e.g., Java, C++).
  • Flexibility in PHP's type system comes at the cost of performance and potential bugs.
  • Recent PHP versions have improved type system and support strict types.

Primitive Types in PHP

Scalar Types

  1. Boolean
    • Represents true or false values.
    • true is printed as 1, false is printed as an empty string.
  2. Integer
    • Numeric values without decimal points (whole numbers).
    • Examples: 1, 2, 3, -5.
  3. Float
    • Numeric values with decimal points (also known as doubles or decimals).
    • Examples: 1.5, 0.1, -15.8.
  4. String
    • Series of characters enclosed within single or double quotes.
    • Examples: 'Hello World', 'Geo'.

Compound Types

  1. Array
    • List of items that can be of different types (integers, booleans, strings, etc.).
    • Defined using square brackets ([]).
    • Printed using print_r function for readability.
  2. Object
  3. Callable
  4. Iterable

Special Types

  1. Resource
  2. Null
    • Represents a variable with no value.

Pseudo Types

  1. Mixed
  2. Void

Identifying Variable Types

  • gettype(): Returns the type of the variable.
    • Example: echo gettype($variable);
  • var_dump(): Prints detailed information about the variable, including type.
    • Example: var_dump($variable);

Type Hinting

  • Specify expected data types for function parameters and returns.
  • Example: function sum(int $x, int $y): int { return $x + $y; } echo sum(2, 3); // Output: 5
  • PHP uses type coercion to convert types dynamically when needed.
  • Type hinting improves code reliability and prevents unexpected bugs.

Strict Types

  • Enable strict types to enforce type requirements strictly.
  • Declared at the top of the PHP file: declare(strict_types=1);
  • Example: declare(strict_types=1); function sum(int $x, int $y): int { return $x + $y; } echo sum(2, '3'); // Causes fatal error
  • In strict mode, integers can still be passed to functions expecting floats.

Typecasting

  • Force a variable to be a specific type using parentheses and type name.
  • Example: $x = '5'; $x = (int)$x; // Casts string '5' to integer 5 var_dump($x); // int(5)

Additional Resources

  • For more detailed information, check out useful links provided in the description.

Conclusion

  • PHP offers a flexible type system that has its advantages and limitations.
  • Understanding and utilizing different data types, type hinting, strict types, and typecasting can lead to more reliable and maintainable code.

Thank you for watching! Please like and subscribe for more in-depth videos on PHP types and other topics!