{
    "slug": "null_reference",
    "term": "Null Reference Errors",
    "category": "php",
    "difficulty": "beginner",
    "short": "Errors caused by calling methods or accessing properties on null — PHP's 'Call to a member function X() on null' and JavaScript's 'Cannot read properties of null' are the most common runtime errors in both languages.",
    "long": "A null reference error occurs when code assumes a variable holds an object but it holds null instead. In PHP: $user->getName() when $user is null throws 'Call to a member function getName() on null'. Common causes: database queries that return null when no record is found (User::find($id) returns null if the user does not exist); optional relationships not loaded; functions that return null on failure without signalling this in the type signature. Solutions: null checks (if ($user !== null)); nullsafe operator (PHP 8.0+: $user?->getName()); strict return types and null coalescing ($user ?? throw new NotFoundException()); using findOrFail() in Eloquent which throws ModelNotFoundException instead of returning null. In JavaScript: optional chaining (user?.name) prevents the error. PHP 8.0's nullsafe operator (?->) chains method calls that short-circuit to null if any step is null.",
    "aliases": [
        "null pointer",
        "null reference",
        "Call to member function on null",
        "NullPointerException",
        "nullsafe operator",
        "null check"
    ],
    "tags": [
        "php",
        "null",
        "errors",
        "nullsafe",
        "debugging",
        "types"
    ],
    "misconception": "Checking for null everywhere with if ($x !== null) is the correct defensive approach. Null checks scattered throughout code indicate a design problem — the question is why the value can be null at that point. The better approach is to make nullability explicit in type signatures (function findUser(): ?User), handle null at the boundary where it enters the system (throw early if required data is missing), and use PHP 8's nullsafe operator for optional chains. Defensive null checks deep in business logic hide the real issue.",
    "why_it_matters": "Null reference errors are the most frequent runtime error in PHP applications. They appear when a database record is not found, an optional field is unset, or a service returns null on failure. Understanding where null comes from and handling it at the correct layer — the data access layer, not scattered throughout business logic — produces more robust code. PHP 8's nullsafe operator (?->) makes null-safe chains readable without nested if-blocks.",
    "common_mistakes": [
        "Using User::find($id) without checking for null — use findOrFail($id) to throw an exception, or check $user !== null before use.",
        "Accessing relationship properties without checking if the relationship is loaded — $post->author->name throws if author is null (no related record).",
        "Not declaring return types as nullable (?User) when a function can return null — the type signature should communicate nullability.",
        "Suppressing the error with @ instead of handling it — @$user->name silences the error but the variable is still null and the behaviour is undefined."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "php_type_error",
        "nullsafe_operator",
        "php_cli",
        "debugging"
    ],
    "prerequisites": [],
    "refs": [
        "https://www.php.net/manual/en/language.oop5.nullsafe.php"
    ],
    "bad_code": "// No null check — throws on missing user\n$user = User::find($id);\necho $user->getName(); // 'Call to member function on null'\n\n// Nested null checks — verbose and easy to miss\nif ($user !== null) {\n    if ($user->getProfile() !== null) {\n        echo $user->getProfile()->getAvatar();\n    }\n}",
    "good_code": "// findOrFail throws ModelNotFoundException — handled centrally\n$user = User::findOrFail($id);\necho $user->getName(); // safe — exception if not found\n\n// PHP 8 nullsafe operator — chains short-circuit to null\necho $user?->getProfile()?->getAvatar() ?? 'default-avatar.png';\n\n// Eloquent: fail fast at the data layer\ntry {\n    $order = Order::findOrFail($orderId);\n} catch (ModelNotFoundException $e) {\n    return response()->json(['error' => 'Order not found'], 404);\n}",
    "quick_fix": "Use findOrFail() in Eloquent to throw on missing records. Use PHP 8 nullsafe operator: $user?->getProfile()?->getAvatar(). Declare nullable return types: function find(): ?User",
    "severity": "medium",
    "effort": "low",
    "created": "2026-03-23",
    "updated": "2026-04-04",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/null_reference",
        "html_url": "https://codeclaritylab.com/glossary/null_reference",
        "json_url": "https://codeclaritylab.com/glossary/null_reference.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Null Reference Errors](https://codeclaritylab.com/glossary/null_reference) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/null_reference"
            }
        }
    }
}