1. 10
    Type casting in PHP
    2m 5s

Type casting in PHP

Mark Shust
InstructorMark Shust
Share this video with your friends

Social Share Links

Send Tweet

Sometimes PHP's automatic data type assignment just doesn't work for your needs. In this case, you can cast a type to a specific variable.

Instructor: [0:00] Let's say that we didn't like how PHP assigned a string for the title and an integer for the number of posts. Even though that's exactly what we wanted, just follow along for a moment. We are able to cast variables as different types at the time they are created. This forces these types to be the exact type that we specify.

[0:19] We can do this by adding parentheses before our variable assignment and then specifying the type we wish to cast this variable to inside the parentheses. For example, let's say we wanted this to be an integer. We can type integer and then save this file.

[0:39] When we refresh the page, we'll see that something happened. PHP took the string, and since it was cast to an integer, it converted that string to the closest representation of that that it could, which here is a zero. We will notice that the call to getType also changed to confirm this variable is now in fact an integer.

[1:00] Let's do the same for numPosts, but we will make it a string instead. When we refresh the page, this time the only thing that changed is the data type. This is because PHP basically just wraps our integer in quotes.

[1:18] This is also what PhpStorm is complaining about, that cast can be replaced with "10" in quotes. We already know that, but this is a good demonstration of what's going on here.

[1:31] You can cast a variable to the many data types of an integer, Boolean, float, string, array, object, or you can cast it to null with the unset keyword. Note also from the screenshot that there are shortcuts for integer and Boolean as int and Bool respectively.

[1:51] It's actually more common than not to see these shorter abbreviations, one referencing data types. Let's change our integer to int. We can see that it has the same output.