-
Notifications
You must be signed in to change notification settings - Fork 8k
Description
Description
TL;DR
PHP has no built-in way to check whether a variable or property has actually been assigned, as opposed to simply being null or not existing. isset() can’t tell the difference between “assigned null” and “not assigned,” and nothing else works consistently. A function like is_assigned() would solve this.
Full
Right now PHP has no reliable way to check if a variable, array key, or object property has actually been assigned, independent of its value.
isset() doesn’t help, because it returns false for both cases:
- when the variable/property is not defined
- when it’s defined but explicitly set to
null
property_exists() doesn’t help either, because it reports properties as existing even if they were never assigned (just declared on the class).
get_object_vars() kind of works for objects, because it only lists assigned properties, even if they're assigned null. But this only works for objects, not variables. Reflection can detect uninitialized typed properties, but not untyped ones, and not variables or arrays.
So there’s no general solution in PHP today to tell the difference between:
- a variable/property that was never assigned
- a variable/property that was assigned
null
This distinction matters when building DTOs, serializers, hydrators, ORMs, or anything where “user assigned null” is different from “value was never provided.”
It would help a lot if PHP had something like:
is_assigned($var);
// or
is_assigned($myClass->prop);which returns true if the variable/property/array key has ever been assigned, even if the assigned value is null, and false if it was never assigned or doesn’t exist.
This wouldn’t break anything and would fill a long-standing gap in the language where userland code simply cannot make this distinction.