Table of Contents

PHP RFC: Types for Local Variables

Introduction

During the last releases of the language the support for types is increasing. We can already add types in a lot of contexts:

Types can bring more confidence when writing code, they can shield applications from unexpected bugs and issues and improve the readability and maintainability of the codebase.

Adding the support for declaring types on local variables is a new step towards the direction that the language has been adding support for types and it's one step closer to adding support for generics later on.

Proposal

This RFC proposes to add a straightforward way of declaring types for local variables:

function foo() {
    $myString = 'foo'; // Current syntax
}
 
function foo() {
    string $myString = 'foo'; // Proposed syntax
}

When typing local variables, if a new assignment to it results in a different type, then a TypeError should be thrown:

function foo() {
    $myString = 'foo';
    $myString = false; // Currently is ok
}
 
function foo() {
    string $myString = 'foo';
    $myString = false; // Proposed - Throw a TypeError
}

When working with arrays, we can also type the elements of the array:

function foo() {
    $myArray = ['foo', 'bar']; // Current syntax
}
 
function foo() {
    array<string> $myArray = ['foo', 'bar']; // Proposed syntax
    // The above would be the same as defining it as array<int, string>
}

Associate arrays can also have the type for the keys and the elements:

function foo() {
    $myArray = ['foo' => 'bar', 'test' => 'testing']; // Current syntax
}
 
function foo() {
    array<string, string> $myArray = ['foo' => 'bar', 'test' => 'testing']; // Proposed syntax
}

P.S.:The support for adding types to array elements and keys can also be extended to Function Arguments, Function Return and Class properties since currently, it's not possible to do that.

Implicitly, all variables that don't have a type declared should be considered to have the type mixed:

function foo() {
    $myString = 'foo'; // Should be interpreted as: mixed $myString = 'foo';
}

Backward Incompatible Changes

None, since this would be optional.

Proposed PHP Version(s)

8.3 if possible or 9.0.

Impact on extensions

None so far.