PHP data type assignments
Note that we didn’t assign a data type when we created our title variable. This is because PHP is considered a “loosely typed language”. In most other languages, you would need to define
$title as a string at the place the variable assignment takes place.
Let’s create a
<p> tag and within it, we will use a short echo tag to display the result of a php function named
gettype(). We’ll pass in the
$title variable as an argument to that function.
<?php $title = 'My Blog'; ?> <h1><?= $title ?></h1> <p><?= gettype($title) ?></p>
When we refresh our page, we’ll see that type is indeed a string.
Let’s create a new variable named
$numPosts. I generally really dislike using abbreviations in my code, but num is pretty common, and will make it a bit easier to digest.
Let’s set it to 10. Then, we’ll create an h2 tag to display that number:
<?php $title = 'My Blog'; $numPosts = 10; ?> <h1><?= $title ?></h1> <p><?= gettype($title) ?></p> <h2><?= $numPosts ?> posts</h2>
Refreshing, we’ll see 10 as expected. Let’s add another call to
gettype() to confirm what type of variable this is:
<?php $title = 'My Blog'; $numPosts = 10; ?> <h1><?= $title ?></h1> <p><?= gettype($title) ?></p> <h2><?= $numPosts ?></h2> <p><?= gettype($numPosts) ?></p>
We can confirm this is an integer! Note how we didn’t strictly define a data type when creating either of these variables. Based on their data value at the time they are created, PHP infers which data type this variable should be, and automatically assigns it for us. Neat!
A little tangent about
gettype: we used it, but didn’t really talk about it.
gettype is actually a built-in PHP function, and not a language construct. In PhpStorm you can Cmd+click, or Ctrl+click on Windows, into the function to read the signature of which types of arguments it expects and what value is returned, get a description of the function (scroll to docblock), and even follow a link to the full documentation on PHP’s website.
There are thousands of built-in functions in PHP, so this documentation is extremely helpful. Don’t be concerned with memorizing all of these functions. I’ve been programming in PHP for over 20 years and I probably only know a fraction of them! You’ll slowly become familiar with more functions as you need to use them, as you continue to work more with the language. We’ll touch base on quite a few more built-in PHP functions later in this course.