[Solution] PHP Fatal Error — Uncaught Error & Out of Memory Fix

A PHP fatal error is a runtime error that causes PHP to stop executing the script immediately. Unlike warnings and notices, fatal errors halt all processing and typically indicate a serious problem that must be fixed. Common fatal errors include uncaught exceptions, out-of-memory conditions, and calls to undefined functions.

Common Fatal Errors and Fixes

1. Call to Undefined Function

This happens when you call a function that doesn’t exist or when a required extension is not loaded.

// WRONG — function does not exist
<?php
json_encode_assoc($data); // undefined function
?>

Fix: Use the correct function name.

// CORRECT
<?php
json_encode($data); // built-in PHP function
?>

If the function comes from an extension, check it is enabled:

php -m | grep json

2. Call to Undefined Method or Class

// WRONG — method does not exist on this class
<?php
class User {
    public $name = "Alice";
}

$user = new User();
echo $user->getAge(); // fatal error: undefined method
?>

Fix: Define the method before calling it.

// CORRECT
<?php
class User {
    public $name = "Alice";
    public $age = 30;

    public function getAge(): int {
        return $this->age;
    }
}

$user = new User();
echo $user->getAge(); // 30
?>

3. Out of Memory Error

PHP has a default memory limit (typically 128 MB). Exceeding it produces a fatal error.

// WRONG — allocating too much memory
<?php
$data = [];
for ($i = 0; $i < 100000000; $i++) {
    $data[] = str_repeat("x", 1000); // eventually runs out of memory
}
?>

Fix: Increase the memory limit or process data in chunks.

// CORRECT — increase memory limit
<?php
ini_set('memory_limit', '256M');
// ... processing code
?>

Better approach — process data in chunks:

// CORRECT — process in chunks
<?php
$handle = fopen("largefile.csv", "r");
if ($handle) {
    $chunk = [];
    while (($line = fgets($handle)) !== false) {
        $chunk[] = trim($line);
        if (count($chunk) >= 1000) {
            process_chunk($chunk);
            $chunk = [];
        }
    }
    if (!empty($chunk)) {
        process_chunk($chunk);
    }
    fclose($handle);
}
?>

4. require/include Failed

Missing files cause a fatal error.

// WRONG — file does not exist
<?php
require_once 'config/database.php'; // fatal error if missing
?>

Fix: Verify the file exists before requiring it.

// CORRECT
<?php
$file = __DIR__ . '/config/database.php';
if (file_exists($file)) {
    require_once $file;
} else {
    die("Configuration file not found: {$file}");
}
?>

5. Uncaught Exception

An uncaught exception results in a fatal error.

// WRONG — no try/catch
<?php
function divide(int $a, int $b): int {
    if ($b === 0) {
        throw new InvalidArgumentException("Division by zero");
    }
    return $a / $b;
}

echo divide(10, 0); // fatal error: uncaught exception
?>

Fix: Wrap exception-throwing code in try/catch.

// CORRECT
<?php
function divide(int $a, int $b): int {
    if ($b === 0) {
        throw new InvalidArgumentException("Division by zero");
    }
    return $a / $b;
}

try {
    echo divide(10, 0);
} catch (InvalidArgumentException $e) {
    echo "Error: " . $e->getMessage();
}
?>

6. Type Error (PHP 7+)

Passing a wrong type to a function with strict typing produces a fatal error.

// WRONG — type mismatch
<?php
declare(strict_types=1);

function add(int $a, int $b): int {
    return $a + $b;
}

echo add("hello", 5); // fatal error: TypeError
?>

Fix: Pass the correct type.

// CORRECT
<?php
declare(strict_types=1);

function add(int $a, int $b): int {
    return $a + $b;
}

echo add(3, 5); // 8
?>

Debugging Fatal Errors

Enable Error Display

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
?>

Use the Error Log

# Find the error log location
php -r "echo ini_get('error_log');"

# Tail the error log in real time
tail -f /var/log/php_errors.log

Check the Exit Code

php myfile.php
echo $? # non-zero exit code indicates a fatal error

Summary

Error TypeFix
Undefined functionVerify function name and check loaded extensions
Undefined methodDefine the method or correct the class name
Out of memoryIncrease memory_limit or process in chunks
require/include failedUse file_exists() before requiring
Uncaught exceptionWrap in try/catch blocks
TypeErrorEnsure correct argument types with strict typing

Best Practices

  • Always enable error_reporting = E_ALL in development.
  • Use try/catch around any code that can throw exceptions.
  • Process large datasets in chunks rather than loading everything into memory.
  • Use file_exists() before require and include.
  • Use declare(strict_types=1) to catch type errors early.