Menu
Coddy logo textTech

Type Declarations

Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 63 of 91.

Type declarations allow you to specify exactly what types your methods and properties should accept and return. This makes your code more predictable and helps catch bugs early - PHP will throw an error if the wrong type is passed.

You can declare types for method parameters, return values, and class properties:

<?php
class Calculator {
    public int $result = 0;
    
    public function add(int $a, int $b): int {
        $this->result = $a + $b;
        return $this->result;
    }
}

$calc = new Calculator();
echo $calc->add(5, 3);

Output:

8

PHP supports several scalar types: int, float, string, bool, and array. You can also use class names, interfaces, and special types like object, mixed, and void for methods that don't return anything:

<?php
class Logger {
    public function log(string $message): void {
        echo "Log: $message";
    }
}

$logger = new Logger();
$logger->log("System started");

Output:

Log: System started

When you type-hint with a class or interface name, PHP ensures only compatible objects are accepted. This is essential for building reliable OOP applications where methods can trust the data they receive without manual validation.

challenge icon

Challenge

Easy

Let's build a temperature converter that demonstrates the power of type declarations. You'll create a system where methods explicitly declare what types they accept and return, making your code self-documenting and catching type errors early.

You'll organize your code across two files:

  • TemperatureConverter.php — Create a TemperatureConverter class that handles conversions between Celsius and Fahrenheit. Your class should:
    • Have a public float property called $lastResult initialized to 0.0
    • Have a method toFahrenheit(float $celsius): float that converts Celsius to Fahrenheit using the formula (celsius * 9/5) + 32, stores the result in $lastResult, and returns it
    • Have a method toCelsius(float $fahrenheit): float that converts Fahrenheit to Celsius using the formula (fahrenheit - 32) * 5/9, stores the result in $lastResult, and returns it
    • Have a method formatResult(string $unit): string that returns the last result formatted as "[lastResult] [unit]" with the result rounded to 2 decimal places
    • Have a method reset(): void that sets $lastResult back to 0.0 and returns nothing
  • main.php — Include the TemperatureConverter file. You'll receive two inputs: a temperature value and a conversion direction ("toF" or "toC").

    Create a TemperatureConverter and perform the appropriate conversion based on the direction. Then print the formatted result using the correct unit symbol ("°F" for Fahrenheit or "°C" for Celsius).

Notice how each method clearly declares its parameter types and return types. The void return type on reset() explicitly communicates that the method performs an action without returning a value. This makes your code's contract clear to anyone reading it.

Cheat sheet

Type declarations specify what types methods and properties should accept and return, helping catch bugs early.

Declare types for method parameters, return values, and class properties:

<?php
class Calculator {
    public int $result = 0;
    
    public function add(int $a, int $b): int {
        $this->result = $a + $b;
        return $this->result;
    }
}

PHP supports scalar types: int, float, string, bool, and array. Also class names, interfaces, and special types like object, mixed, and void.

Use void for methods that don't return anything:

<?php
class Logger {
    public function log(string $message): void {
        echo "Log: $message";
    }
}

Type-hinting with class or interface names ensures only compatible objects are accepted.

Try it yourself

<?php

require_once 'TemperatureConverter.php';

// Read input
$temperature = floatval(trim(fgets(STDIN)));
$direction = trim(fgets(STDIN));

// TODO: Create a TemperatureConverter instance

// TODO: Based on the direction ("toF" or "toC"), perform the appropriate conversion
// - If direction is "toF", convert to Fahrenheit and use unit "°F"
// - If direction is "toC", convert to Celsius and use unit "°C"

// TODO: Print the formatted result using formatResult() with the correct unit symbol

?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming