Why type casting of values is important in php?

What is the difference between:

$var = (string) "a";
//And
$var = "a";

I sometimes come into debate with some developers, on the need to cast php variables values.

There are no clear documentations on this subject, so this is my interpretation.

1. Can php cast variables?
First of all, you have to know that php can not cast variables, but only values.

2. Is php an interpreted or compiled language?
Php is a on the fly compiled language, and not interpreted like many developers tell it.

It then becomes important to learn how are saved variables inside your computer.

3. How do variables are saved inside our computers?

  • When a variable is declared, in reality, we’re asking to the computer, the permission to create some space in the RAM (Random Access Memory), for this variable.
    (One space for the variable name called address, one space for its value).
  • Without RAM, our program will be unable to memorize our variables.

  • Depending on the type of declared variable, thus, a more or less memory space is allocated for the value (remember that php can’t cast a variable, just its value).

4. Then, what benefits to cast values?

  • Save time for variables assignment in memory (although negligible with our latest machines).
  • Better code clarity and readability, let me explain.

  • $varA = 'a';
    $varB = 0;
    var_dump($varA == $varB); //equals true, this is not what we expected
    

    Php first analyzes variables values and then casts them. for this comparison, it will convert ‘a’ string into integer. This will result to 0.

    One solution would be to first check the $varB type before comparison like this:

    $varA = 'a';
    $varB = 0;
    if (is_string($varB)) {
       var_dump($varA == $varB);
    }
    

    But, the best practice is to cast the values, upstream.

    $varA = (string) 'a';
    $varB = (string) 0;
    var_dump($var1 == $varB); //equals false, what we expected
    

    I see you coming!!! Of course, we could also write:

    $varA = 'a';
    $varB = '0';
    

    But in my opinion, it’s less readable.

    Everyone has its method. The main important is to test variables before using them.
    There are many other examples, but it is not the purpose of this post, if you have your opinion, you are invited to share it.

    Advertisements
    Why type casting of values is important in php?

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s