Phonexay Singharatsavong

Phonexay Singharatsavong

Who am I?

I have been programming for over 20 years and wanted to start a blog about things I have learned over the years, am still learning, and will be learning, feel free to contact me.


What I write about


Recent Posts

PHP Type Hinting

I have been programming in PHP for awhile, I started programming with PHP when it the version was 4.0 and now it's 7.2. One of the things that you didn't need to worry about to much in PHP was the types you passed to a function, versus a language like Java. Recently, I've been using type hinting more and more in PHP and have grown to like it. It was introduce in PHP 5.0, but has grown to allow more types.

What is type hinting? It allows for the ability to specify the expected data type of an argument in a function declaration. As PHP has grown over the year, it has also grown in complexity and at times trying to figure out what can be pass to a function cannot be as clear or easily readable. This is where type hinting comes in:

Example:

function addTogether(number, name) {
    return number . name;
}

The function looks straight forward right, but you don't know what number and name are suppose to be and this isn't as readable as it should be.

Updated Example:

function addTogether(int number, string name) {
    return number . name;
}

With the updated example, it is much easier to read and also you can tell if the function is doing what it is suppose to do(that isn't always obvious if you are inheriting someone's code) or there might be a possible bug. With PHP type hinting you can specify classes as well and other primitive types in PHP, as of PHP 7.2 you can use an object.

When I first started using type hinting in PHP, it felt strange, mostly PHP started off without using any types, but now the practice has grown on me. It's also helpful if you are using an ide like PHP Storm to see what a function takes by highlighting or rollover it. If you have any questions as always feel free to hit me up.

Here is a link for more info: https://www.php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration