PHP 8.5.0 RC 2 available for testing

ReflectionParameter::allowsNull

(PHP 5, PHP 7, PHP 8)

ReflectionParameter::allowsNullVerifica si el valor null está permitido como valor del argumento

Descripción

public ReflectionParameter::allowsNull(): bool

Verifica si el valor null está permitido como valor del argumento.

Parámetros

Esta función no contiene ningún parámetro.

Valores devueltos

true si el valor null está permitido como valor del argumento, false en caso contrario.

Ver también

add a note

User Contributed Notes 2 notes

up
13
Geoffrey LAURENT
12 years ago
The allowsNull method look if arguments have a type.
If a type is defined, null is allowed only if default value is null.

<?php
function myfunction ( $param ) {

}

echo (new
ReflectionFunction("myfunction"))->getParameters()[0]->allowsNull() ? "true":"false";

?>

Result : true

<?php
function myfunction ( stdClass $param ) {

}

echo (new
ReflectionFunction("myfunction"))->getParameters()[0]->allowsNull() ? "true":"false";

?>

Result : false

<?php
function myfunction ( stdClass $param = null ) {

}

echo (new
ReflectionFunction("myfunction"))->getParameters()[0]->allowsNull() ? "true":"false";
?>

Result : true
up
0
those-cradle-frays at duck dot com
1 day ago
The note about detecting nullability on a parameter predates "?type" and other union types. Null isn't expected to be the default if there's a defined type that allows it ("?int", "mixed", "int|string|null", etc.).

<?php
function foo($bar) { }
(new
ReflectionFunction('foo'))->getParameters()[0]->allowsNull();
// true

function foo(string $bar) { }
(new
ReflectionFunction('foo'))->getParameters()[0]->allowsNull();
// false

function foo(?string $bar) { }
(new
ReflectionFunction('foo'))->getParameters()[0]->allowsNull();
// true

function foo(?string $bar = 'baz') { }
(new
ReflectionFunction('foo'))->getParameters()[0]->allowsNull();
// true (default string doesn't matter)

// Note: Raises E_DEPRECATED, implicitly making parameter nullable
function foo(string $bar = null) { }
(new
ReflectionFunction('foo'))->getParameters()[0]->allowsNull();
// true (even in strict mode, PHP <= 8)
?>
To Top