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:
8PHP 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 startedWhen 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
EasyLet'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 aTemperatureConverterclass that handles conversions between Celsius and Fahrenheit. Your class should:- Have a public
floatproperty called$lastResultinitialized to0.0 - Have a method
toFahrenheit(float $celsius): floatthat 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): floatthat 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): stringthat returns the last result formatted as"[lastResult] [unit]"with the result rounded to 2 decimal places - Have a method
reset(): voidthat sets$lastResultback to0.0and returns nothing
- Have a public
main.php— Include the TemperatureConverter file. You'll receive two inputs: a temperature value and a conversion direction ("toF"or"toC").Create a
TemperatureConverterand 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
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern