PHP: Hypertext Preprocessor (original) (raw)
Type declarations
Type declarations can be added to function arguments, return values, as of PHP 7.4.0, class properties, and as of PHP 8.3.0, class constants. They ensure that the value is of the specified type at call time, otherwise a TypeError is thrown.
Every single type that PHP supports, with the exception ofresource can be used within a user-land type declaration. This page contains a changelog of availability of the different types and documentation about usage of them in type declarations.
Note:
When a class implements an interface method or reimplements a method which has already been defined by a parent class, it has to be compatible with the aforementioned definition. A method is compatible if it follows thevariance rules.
Changelog
Version | Description |
---|---|
8.3.0 | Support for class, interface, trait, and enum constant typing has been added. |
8.2.0 | Support for DNF types has been added. |
8.2.0 | Support for the literal type true has been added. |
8.2.0 | The types null and false can now be used standalone. |
8.1.0 | Support for intersection types has been added. |
8.1.0 | Returning by reference from a void function is now deprecated. |
8.1.0 | Support for the return only type never has been added. |
8.0.0 | Support for mixed has been added. |
8.0.0 | Support for the return only type static has been added. |
8.0.0 | Support for union types has been added. |
7.4.0 | Support for class properties typing has been added. |
7.2.0 | Support for object has been added. |
7.1.0 | Support for iterable has been added. |
7.1.0 | Support for void has been added. |
7.1.0 | Support for nullable types has been added. |
Atomic Types Usage Notes
Atomic types have straight forward behaviour with some minor caveats which are described in this section.
Scalar types
Warning
Name aliases for scalar types (bool, int,float, string) are not supported. Instead, they are treated as class or interface names. For example, using boolean
as a type declaration will require the value to be an instanceof the class or interfaceboolean
, rather than of type bool:
<?php function test(boolean $param) {} test(true); ?>
Output of the above example in PHP 8:
Warning: "boolean" will be interpreted as a class name. Did you mean "bool"? Write "\boolean" to suppress this warning in /in/9YrUX on line 2
Fatal error: Uncaught TypeError: test(): Argument #1 ($param) must be of type boolean, bool given, called in - on line 3 and defined in -:2 Stack trace: #0 -(3): test(true) #1 {main} thrown in - on line 2
void
Note:
Returning by reference from a void function is deprecated as of PHP 8.1.0, because such a function is contradictory. Previously, it already emitted the following**
[E_NOTICE](errorfunc.constants.php#constant.e-notice)
** when called:Only variable references should be returned by reference.
<?php function &test(): void {} ?>
Callable types
This type cannot be used as a class property type declaration.
Note: It is not possible to specify the signature of the function.
Type declarations on pass-by-reference Parameters
If a pass-by-reference parameter has a type declaration, the type of the variable is only checked on function entry, at the beginning of the call, but not when the function returns. This means that a function can change the type of variable reference.
Example #1 Typed pass-by-reference Parameters
<?php function array_baz(array &$param) { $param = 1; } $var = []; array_baz($var); var_dump($var); array_baz($var); ?>
The above example will output something similar to:
int(1)
Fatal error: Uncaught TypeError: array_baz(): Argument #1 ($param) must be of type array, int given, called in - on line 9 and defined in -:2 Stack trace: #0 -(9): array_baz(1) #1 {main} thrown in - on line 2
Composite Types Usage Notes
Composite type declarations are subject to a couple of restrictions and will perform a redundancy check at compile time to prevent simple bugs.
Caution
Prior to PHP 8.2.0, and the introduction of DNF types, it was not possible to combine intersection types with union types.
Union types
Warning
It is not possible to combine the two singleton types false and true together in a union type. Use bool instead.
Caution
Prior to PHP 8.2.0, as false and null could not be used as standalone types, a union type comprised of only these types was not permitted. This comprises the following types:false, false|null
, and ?false
.
Nullable type syntactic sugar
A single base type declaration can be marked nullable by prefixing the type with a question mark (?
). Thus ?T
and T|null
are identical.
Note: This syntax is supported as of PHP 7.1.0, and predates generalized union types support.
Note:
It is also possible to achieve nullable arguments by making
null
the default value. This is not recommended as if the default value is changed in a child class a type compatibility violation will be raised as thenull type will need to be added to the type declaration. This behavior is also deprecated since PHP 8.4.Example #2 Old way to make arguments nullable
`<?php
class C {}function
f(C $c = null) {
var_dump($c);
}f(new C);
f(null);
?>`The above example will output:
Duplicate and redundant types
To catch simple bugs in composite type declarations, redundant types that can be detected without performing class loading will result in a compile-time error. This includes:
- Each name-resolved type may only occur once. Types such as
int|string|INT
orCountable&Traversable&COUNTABLE
result in an error. - Using mixed results in an error.
- For union types:
- For intersection types:
- Using a type which is not a class-type results in an error.
- Using either self, parent, orstatic results in an error.
- For DNF types:
- If a more generic type is used, the more restrictive one is redundant.
- Using two identical intersection types.
Note: This does not guarantee that the type is “minimal”, because doing so would require loading all used class types.
For example, if A
and B
are class aliases, then A|B
remains a legal union type, even though it could be reduced to either A
orB
. Similarly, if class B extends A {}
, then A|B
is also a legal union type, even though it could be reduced to justA
.
<?php function foo(): int|INT {} // Disallowed function foo(): bool|false {} // Disallowed function foo(): int&Traversable {} // Disallowed function foo(): self&Traversable {} // Disalloweduse A as B; function foo(): A|B {} // Disallowed ("use" is part of name resolution) function foo(): A&B {} // Disallowed ("use" is part of name resolution)class_alias('X', 'Y'); function foo(): X|Y {} // Allowed (redundancy is only known at runtime) function foo(): X&Y {} // Allowed (redundancy is only known at runtime) ?>
Examples
Example #3 Basic class type declaration
`<?php
class C {}
class D extends C {}// This doesn't extend C.
class E {}
function
f(C $c) {
echo get_class($c)."\n";
}f(new C);
f(new D);
f(new E);
?>`
Output of the above example in PHP 8:
C D
Fatal error: Uncaught TypeError: f(): Argument #1 ($c) must be of type C, E given, called in /in/gLonb on line 14 and defined in /in/gLonb:8 Stack trace: #0 -(14): f(Object(E)) #1 {main} thrown in - on line 8
Example #4 Basic interface type declaration
`<?php
interface I { public function f(); }
class C implements I { public function f() {} }// This doesn't implement I.
class E {}
function
f(I $i) {
echo get_class($i)."\n";
}f(new C);
f(new E);
?>`
Output of the above example in PHP 8:
C
Fatal error: Uncaught TypeError: f(): Argument #1 ($i) must be of type I, E given, called in - on line 13 and defined in -:8 Stack trace: #0 -(13): f(Object(E)) #1 {main} thrown in - on line 8
Example #5 Basic return type declaration
<?php function sum($a, $b): float { return <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>a</mi><mo>+</mo></mrow><annotation encoding="application/x-tex">a + </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6667em;vertical-align:-0.0833em;"></span><span class="mord mathnormal">a</span><span class="mord">+</span></span></span></span>b; }// Note that a float will be returned. var_dump(sum(1, 2)); ?>
The above example will output:
Example #6 Returning an object
`<?php
class C {}
function
getC(): C {
return new C;
}var_dump(getC());
?>`
The above example will output:
Example #7 Nullable argument type declaration
`<?php
class C {}
function
f(?C $c) {
var_dump($c);
}f(new C);
f(null);
?>`
The above example will output:
Example #8 Nullable return type declaration
<?php function get_item(): ?string { if (isset($_GET['item'])) { return $_GET['item']; } else { return null; } } ?>
Example #9 Class property type declaration
`<?php
class User {
public static string $foo = 'foo';
public
int $id;
public string $username;
public function
__construct(int id,stringid, string id,stringusername) { this−>id=this->id = this−>id=id; this−>username=this->username = this−>username=username;
}
}
?>`
Strict typing
By default, PHP will coerce values of the wrong type into the expected scalar type declaration if possible. For example, a function that is given an int for a parameter that expects a string will get a variable of type string.
It is possible to enable strict mode on a per-file basis. In strict mode, only a value corresponding exactly to the type declaration will be accepted, otherwise a TypeError will be thrown. The only exception to this rule is that an int value will pass a float type declaration.
Warning
Function calls from within internal functions will not be affected by the strict_types
declaration.
To enable strict mode, the declare statement is used with thestrict_types
declaration:
Note:
Strict typing applies to function calls made from_within_ the file with strict typing enabled, not to the functions declared within that file. If a file without strict typing enabled makes a call to a function that was defined in a file with strict typing, the caller's preference (coercive typing) will be respected, and the value will be coerced.
Note:
Strict typing is only defined for scalar type declarations.
Example #10 Strict typing for arguments values
`<?php
declare(strict_types=1);
function
sum(int a,inta, int a,intb) {
return a+a + a+b;
}var_dump(sum(1, 2));
var_dump(sum(1.5, 2.5));
?>`
Output of the above example in PHP 8:
int(3)
Fatal error: Uncaught TypeError: sum(): Argument #1 ($a) must be of type int, float given, called in - on line 9 and defined in -:4 Stack trace: #0 -(9): sum(1.5, 2.5) #1 {main} thrown in - on line 4
Example #11 Coercive typing for argument values
<?php function sum(int <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>a</mi><mo separator="true">,</mo><mi>i</mi><mi>n</mi><mi>t</mi></mrow><annotation encoding="application/x-tex">a, int </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.854em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">a</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">in</span><span class="mord mathnormal">t</span></span></span></span>b) { return <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>a</mi><mo>+</mo></mrow><annotation encoding="application/x-tex">a + </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.6667em;vertical-align:-0.0833em;"></span><span class="mord mathnormal">a</span><span class="mord">+</span></span></span></span>b; }var_dump(sum(1, 2));// These will be coerced to integers: note the output below! var_dump(sum(1.5, 2.5)); ?>
The above example will output:
Example #12 Strict typing for return values
`<?php
declare(strict_types=1);
function
sum($a, $b): int {
return a+a + a+b;
}var_dump(sum(1, 2));
var_dump(sum(1, 2.5));
?>`
The above example will output:
int(3)
Fatal error: Uncaught TypeError: sum(): Return value must be of type int, float returned in -:5 Stack trace: #0 -(9): sum(1, 2.5) #1 {main} thrown in - on line 5
Found A Problem?
toinenkayt (ta at ta) [iwonderr] gmail d ¶
3 years ago
`While waiting for native support for typed arrays, here are a couple of alternative ways to ensure strong typing of arrays by abusing variadic functions. The performance of these methods is a mystery to the writer and so the responsibility of benchmarking them falls unto the reader.
PHP 5.6 added the splat operator (...) which is used to unpack arrays to be used as function arguments. PHP 7.0 added scalar type hints. Latter versions of PHP have further improved the type system. With these additions and improvements, it is possible to have a decent support for typed arrays.
arg)(...arg)(...arg)(...ints); // Or to avoid cluttering memory with too many closures typeArrayNullInt(...$ints);/* ... */ } function doSomethingElse(?int ...$ints): void { /* ... */ }$ints = [1,2,3,4,null]; doSomething ($ints); doSomethingElse (...$ints); ?>Both methods work with all type declarations. The key idea here is to have the functions throw a runtime error if they encounter a typing violation. The typing method used in doSomethingElse is cleaner of the two but it disallows having any other parameters after the variadic parameter. It also requires the call site to be aware of this typing implementation and unpack the array. The method used in doSomething is messier but it does not require the call site to be aware of the typing method as the unpacking is performed within the function. It is also less ambiguous as the doSomethingElse would also accept n individual parameters where as doSomething only accepts an array. doSomething's method is also easier to strip away if native typed array support is ever added to PHP. Both of these methods only work for input parameters. An array return value type check would need to take place at the call site.
If strict_types is not enabled, it may be desirable to return the coerced scalar values from the type check function (e.g. floats and strings become integers) to ensure proper typing.
`
3 years ago
`` The documentation lacks the information, that it's possible to change the return type of a method defined in an interface when the interface's methods return type is defined as mixed
.
From the RFC:
"The mixed return type could be narrowed in a subclass as this is covariant and is allowed in LSP." (https://wiki.php.net/rfc/mixed_type_v2)
This means the following code is valid in PHP 8.0:
apfel()); ?>You can see the result here: https://3v4l.org/PXDB6
``
3 months ago
`For DNF type declarations (which lack an example), they're a mix of intersection and union types that look like this:
It's a union type where some of its options are intersection types, which are wrapped in parentheses ($f is something that is either a c1, or something that is both a c2 and a c3).`