What is null/nil in PHP and how to work with it?
Hello everyone! I'm new to PHP and trying to understand the null type (or nil, as it's sometimes called). The documentation says it's a special value meaning "absence of value", but in practice I'm getting strange errors.
For example, I write simple code:
\n\n$user = getUserFromDatabase($id); // the function may return null if user is not found\necho $user->name;\n\n\nIf the user is found, everything works, but if not — I get an error "Trying to get property 'name' of non-object". I understand that I need to check for null, but how to do it correctly? I tried if ($user != null) and if (is_null($user)), but sometimes the behavior is different. I also heard about the ?
No answers yet.
Log in to leave an answer