PHP - Scalar Type Declarations

Hello, aspiring programmers! Today, we're going to embark on an exciting journey into the world of PHP, specifically focusing on Scalar Type Declarations. Don't worry if these words sound like gibberish right now – by the end of this tutorial, you'll be throwing these terms around like a seasoned developer!

PHP - Scalar Type Declarations

What are Scalar Type Declarations?

Before we dive in, let's break down what "Scalar Type Declarations" actually mean. In programming, a "scalar" is a single value, like a number or a string of text. "Type declaration" is a fancy way of saying we're telling PHP what kind of data we expect a function to receive or return.

Imagine you're running a lemonade stand. You wouldn't want someone to hand you a basketball when you ask for lemons, right? That's essentially what type declarations do – they make sure your code gets the right kind of data to work with.

Scalar Type Declarations in PHP 7

PHP 7 introduced a game-changing feature: the ability to declare scalar types for function parameters and return values. This was a big deal because it helped catch errors early and made code more reliable.

Let's look at a simple example:

function addNumbers(int $a, int $b): int {
    return $a + $b;
}

echo addNumbers(5, 10); // Output: 15

In this code:

  • int $a, int $b: We're saying that both $a and $b should be integers.
  • : int: This part after the function declares that the function will return an integer.

Now, let's try something naughty:

echo addNumbers("5", "10");

Surprise! This still works and outputs 15. But why? Welcome to the world of...

Coercive Mode

By default, PHP 7 operates in what we call "coercive mode". It's like having a really understanding friend who tries to make sense of what you're saying, even if you're not being totally clear.

In coercive mode, PHP will try to convert (or "coerce") values to the declared type if possible. So when we passed "5" and "10" as strings, PHP said, "I see what you're trying to do," and converted them to integers.

Here's a table of some common coercions:

Input Declared Type Result
"42" int 42
"3.14" float 3.14
1 string "1"
true int 1

But what if we want PHP to be stricter? Enter...

Strict Mode

Strict mode is like having a teacher who insists on precise answers. To enable strict mode, add this line at the very top of your PHP file:

declare(strict_types=1);

Now, let's try our naughty example again:

declare(strict_types=1);

function addNumbers(int $a, int $b): int {
    return $a + $b;
}

echo addNumbers("5", "10");

Boom! This will now throw a TypeError. PHP is saying, "I asked for integers, and you gave me strings. I'm not happy about this."

Why Use Scalar Type Declarations?

  1. Clearer Code: It's like leaving a note for future you (or other developers). "Hey, this function expects numbers!"

  2. Catch Errors Early: Instead of weird results, you get errors that point directly to the problem.

  3. Better Performance: PHP can optimize code better when it knows exactly what types to expect.

A Real-World Example

Let's say you're building a simple calculator app. Here's how you might use scalar type declarations:

declare(strict_types=1);

class Calculator {
    public function add(float $a, float $b): float {
        return $a + $b;
    }

    public function subtract(float $a, float $b): float {
        return $a - $b;
    }

    public function multiply(float $a, float $b): float {
        return $a * $b;
    }

    public function divide(float $a, float $b): float {
        if ($b == 0) {
            throw new Exception("Cannot divide by zero!");
        }
        return $a / $b;
    }
}

$calc = new Calculator();

echo $calc->add(5.5, 4.5);      // Output: 10
echo $calc->subtract(10, 3);    // Output: 7
echo $calc->multiply(3, 4);     // Output: 12
echo $calc->divide(10, 2);      // Output: 5

// This will throw an error in strict mode
// echo $calc->add("5", "10");

In this example, we've created a Calculator class with methods that all use float type declarations. This ensures that all our calculations are working with numbers, preventing any accidental string concatenation or other type-related mishaps.

Conclusion

Scalar type declarations in PHP are like guardrails on a mountain road. They help keep your code on track and make it easier to spot when something's going wrong. While they might seem a bit fussy at first, trust me – future you will be thankful for the clarity and safety they provide.

Remember, programming is all about clear communication – not just with the computer, but with other developers (including future you!). Type declarations are one more tool in your toolbox to write clearer, safer, and more efficient code.

Now go forth and declare those types! Your code will thank you, and so will your fellow developers. Happy coding!

Credits: Image by storyset