PHP 8.5.0 RC 3 available for testing

ReflectionParameter::allowsNull

(PHP 5, PHP 7, PHP 8)

ReflectionParameter::allowsNullChecks if null is allowed

Descrizione

public ReflectionParameter::allowsNull(): bool

Checks whether the parameter allows null.

Elenco dei parametri

Questa funzione non contiene parametri.

Valori restituiti

true if null is allowed, otherwise false

Vedere anche:

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<?phpfunction myfunction ( stdClass $param = null ) {    }echo (new ReflectionFunction("myfunction"))->getParameters()[0]->allowsNull() ? "true":"false";?>Result : true
up
0
those-cradle-frays at duck dot com
10 days 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.).<?phpfunction foo($bar) { }(new ReflectionFunction('foo'))->getParameters()[0]->allowsNull();// truefunction foo(string $bar) { }(new ReflectionFunction('foo'))->getParameters()[0]->allowsNull();// falsefunction foo(?string $bar) { }(new ReflectionFunction('foo'))->getParameters()[0]->allowsNull();// truefunction foo(?string $bar = 'baz') { }(new ReflectionFunction('foo'))->getParameters()[0]->allowsNull();// true (default string doesn't matter)// Note: Raises E_DEPRECATED, implicitly making parameter nullablefunction foo(string $bar = null) { }(new ReflectionFunction('foo'))->getParameters()[0]->allowsNull();// true (even in strict mode, PHP <= 8)?>
To Top