Errors/PHP

Common PHP Errors

PHP errors including undefined variables, type errors, memory exhaustion, PDO exceptions, and common framework issues.

75 errors documented with step-by-step fixes

Undefined Variable

Warning: Undefined variable $username

You are using a variable that has not been assigned a value in the current scope. Initialize the variable before using it or check if it exists with isset().

Call to Undefined Function

Fatal error: Uncaught Error: Call to undefined function getUsers()

You are calling a function that does not exist. Check for typos in the function name, ensure the file containing the function is included, or verify the extension is enabled.

Call to a Member Function on Null

Fatal error: Uncaught Error: Call to a member function getName() on null

You are calling a method on a variable that is null instead of an object. Check that the variable is properly initialized and that any function returning it does not return null.

Cannot Use Object as Array

Fatal error: Uncaught Error: Cannot use object of type stdClass as array

You are using array syntax on an object. Access object properties with the arrow operator -> instead of bracket notation, or cast the object to an array.

Class Not Found

Fatal error: Uncaught Error: Class 'App\Service\UserService' not found

PHP cannot find the specified class. Verify the namespace, file path, and autoloader configuration match. Run composer dump-autoload if using Composer.

Allowed Memory Size Exhausted

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 65536 bytes)

Your script has used more memory than the configured limit. This usually indicates an infinite loop, loading too much data at once, or a memory leak. Optimize your code to use less memory or increase the limit.

Maximum Execution Time Exceeded

Fatal error: Maximum execution time of 30 seconds exceeded

Your script ran longer than the configured time limit. This usually indicates an infinite loop, a slow external API call, or a heavy database query. Optimize the slow operation or increase the time limit.

Cannot Redeclare Function

Fatal error: Cannot redeclare formatDate() (previously declared in helpers.php:10)

You are defining a function that already exists. This usually happens when a file is included multiple times. Use require_once or include_once, or wrap the function in a function_exists check.

Trying to Access Array Offset on Null

Warning: Trying to access array offset on value of type null

You are using array bracket notation on a null value. The variable you expect to be an array is actually null. Check the source of the data and add a null check.

Division by Zero

Warning: Division by zero

You are dividing a number by zero. Validate that the divisor is not zero before performing the division.

Invalid Argument Supplied for foreach

Warning: Invalid argument supplied for foreach()

You are passing a non-iterable value such as null, false, or a string to a foreach loop. Ensure the variable is an array or iterable before looping.

Headers Already Sent

Warning: Cannot modify header information - headers already sent by (output started at index.php:5)

You are trying to send HTTP headers after output has already been sent to the browser. Move all header(), setcookie(), and session_start() calls before any echo, print, or HTML output.

Undefined Index

Warning: Undefined index: email in /app/register.php on line 12

You are accessing an array key that does not exist. Check if the key exists with isset() or array_key_exists() before accessing it, or use the null coalescing operator.

Undefined Array Key

Warning: Undefined array key "role" in /app/auth.php on line 8

You are accessing an array key that does not exist. This is the PHP 8.0+ version of the undefined index warning. Use isset() or the null coalescing operator ?? before accessing the key.

TypeError: Wrong Argument Type

Fatal error: Uncaught TypeError: Argument #1 ($name) must be of type string, null given

You are passing a value of the wrong type to a function with type declarations. Ensure the argument matches the expected type or make the parameter nullable.

TypeError: Wrong Return Type

Fatal error: Uncaught TypeError: App\Service\UserService::findUser(): Return value must be of type App\Entity\User, null returned

A function returned a value that does not match its declared return type. Either change the return type to be nullable or ensure the function always returns the correct type.

Cannot Use String Offset as Array

Fatal error: Cannot use string offset as an array

You are trying to use nested array syntax on a string variable. The variable you think is a nested array is actually a string. Check the variable type and data structure.

PDO Connection Failed

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] Connection refused

PHP cannot connect to the database server. Verify the host, port, username, password, and that the database server is running and accepting connections.

PDO Query Syntax Error

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax

Your SQL query has a syntax error. Check for missing quotes, incorrect column names, reserved word conflicts, or malformed clauses. Always use prepared statements.

PDO Table Not Found

Fatal error: Uncaught PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'myapp.users' doesn't exist

The database table referenced in your query does not exist. Check the table name for typos, verify you are connected to the correct database, and ensure migrations have been run.

Syntax Error: Unexpected Token

Parse error: syntax error, unexpected token "}"

Your PHP code has a syntax error such as a missing semicolon, unmatched brace, or incorrect structure. Check the line mentioned and the lines immediately before it.

Syntax Error: Unexpected End of File

Parse error: syntax error, unexpected end of file

Your PHP file has an unclosed brace, parenthesis, or string. A block was opened but never closed. Check for missing closing braces or an unterminated string or heredoc.

Cannot Redeclare Class

Fatal error: Cannot redeclare class App\Entity\User (previously declared in /app/src/Entity/User.php:8)

The same class is being declared twice. Use require_once instead of require, or rely on Composer autoloading to prevent double-loading files.

Interface Not Found

Fatal error: Uncaught Error: Interface 'App\Contract\Loggable' not found

PHP cannot find the specified interface. Verify the namespace, file path, and autoloader configuration. Ensure the interface file exists and is properly autoloaded.

json_decode Returns Null

json_decode() returns null with json_last_error(): JSON_ERROR_SYNTAX

The JSON string you are trying to decode is malformed. Validate the JSON syntax, check for BOM characters, trailing commas, or single quotes instead of double quotes.

Session Already Started

Warning: session_start(): Ignoring session_start() because a session is already active

You are calling session_start() when a session is already active. Check if a session exists before starting one using session_status().

Failed to Open Required File

Fatal error: require(): Failed opening required 'config.php' (include_path='.:/usr/share/php')

PHP cannot find the file you are trying to require. The file path is incorrect, the file does not exist, or the include_path does not contain the file's directory.

Permission Denied on File Operation

Warning: file_put_contents(/var/log/app.log): Failed to open stream: Permission denied

PHP does not have permission to read or write the specified file. Check file ownership and permissions, and ensure the web server user has appropriate access.

Failed to Open Stream: No Such File or Directory

Warning: fopen(data/output.csv): Failed to open stream: No such file or directory

The file or directory path does not exist. Create the directory first or check that the file path is correct.

Too Few Arguments to Function

Fatal error: Uncaught ArgumentCountError: Too few arguments to function App\Service::calculate(), 1 passed and exactly 2 expected

You are calling a function with fewer arguments than it requires. Add the missing arguments or give the parameters default values.

Array to String Conversion

Warning: Array to string conversion

You are using an array where a string is expected, such as in echo or string concatenation. Use implode(), json_encode(), or access a specific array element instead.

Undefined Property

Warning: Undefined property: App\Entity\User::$username

You are accessing an object property that does not exist. Check the property name for typos, ensure it is declared in the class, and verify the object is the expected type.

Undefined Constant

Fatal error: Uncaught Error: Undefined constant "APP_ENV"

You are using a constant that has not been defined. Check that the constant is defined with define() or const before it is used, or that the file defining it is loaded.

Cannot Instantiate Abstract Class

Fatal error: Uncaught Error: Cannot instantiate abstract class App\Base\AbstractRepository

You cannot create an instance of an abstract class with new. Create a concrete class that extends the abstract class and instantiate that instead.

Call to Private Method

Fatal error: Uncaught Error: Call to private method App\Entity\User::hashPassword() from scope App\Controller\UserController

You are trying to call a private method from outside its class. Change the visibility to public or protected, or use a public method that internally calls the private one.

Cannot Modify Readonly Property

Fatal error: Uncaught Error: Cannot modify readonly property App\Entity\User::$email

You are trying to change a readonly property after it has been initialized. Readonly properties can only be set once, in the constructor. Create a new object with the updated value instead.

Enum Case Not Found

Fatal error: Uncaught ValueError: "admin" is not a valid backing value for enum "App\Enum\UserRole"

The value you are trying to convert to an enum does not match any of the defined cases. Use tryFrom() instead of from() to handle invalid values gracefully, or verify the value before conversion.

Fiber Not Started Error

Fatal error: Uncaught FiberError: Cannot resume a fiber that is not suspended

You are trying to resume a Fiber that has not been started, has already finished, or is currently running. Call start() first and only resume() after the Fiber has suspended itself.

Implicit Conversion from Float to Int Loses Precision

Deprecated: Implicit conversion from float 3.5 to int loses precision

PHP 8.1+ warns when a float with a fractional part is implicitly converted to an integer. Use an explicit cast (int) or round/floor/ceil to make the conversion intentional.

Unknown Named Parameter

Fatal error: Uncaught Error: Unknown named parameter $colour

You are using a named argument that does not match any parameter name in the function definition. Check for typos in the parameter name.

Unhandled Match Value

Fatal error: Uncaught UnhandledMatchError: Unhandled match case

A match expression received a value that does not match any of the defined arms and has no default case. Add a default arm or handle all possible values.

Intersection Type Error

Fatal error: Uncaught TypeError: App\Service::process(): Argument #1 ($handler) must be of type Countable&Iterator, App\SimpleList given

The argument does not implement all interfaces required by the intersection type. Ensure the class implements every interface listed in the intersection type.

Creation of Dynamic Property is Deprecated

Deprecated: Creation of dynamic property App\Entity\User::$fullName is deprecated

PHP 8.2 deprecated setting undeclared properties on objects. Declare the property in the class definition or use the #[AllowDynamicProperties] attribute.

Typed Property Not Initialized

Fatal error: Uncaught Error: Typed property App\Entity\User::$email must not be accessed before initialization

You are accessing a typed property before it has been assigned a value. Initialize the property in the constructor or give it a default value in the declaration.

cURL Connection Error

cURL error 7: Failed to connect to api.example.com port 443: Connection refused

PHP's cURL cannot reach the remote server. Check the URL, verify the server is running, check DNS resolution, and ensure no firewall is blocking the connection.

cURL SSL Certificate Error

cURL error 60: SSL certificate problem: unable to get local issuer certificate

PHP's cURL cannot verify the SSL certificate. Install or update the CA certificate bundle on the server rather than disabling SSL verification.

Call to Undefined Method

Fatal error: Uncaught Error: Call to undefined method App\Entity\User::getFullName()

You are calling a method that does not exist on the object's class. Check for typos, verify the method is defined, and ensure you have the right object type.

Unknown Named Parameter / Extra Arguments

Fatal error: Uncaught ArgumentCountError: Too many arguments to function trim(), 3 passed and at most 2 expected

You are passing more arguments than the function accepts. Check the function signature and remove the extra arguments.

Non-Static Method Called Statically

Fatal error: Uncaught Error: Non-static method App\Service\UserService::findAll() cannot be called statically

You are using ClassName::method() syntax on a method that is not declared as static. Either make the method static or create an instance of the class first.

Serialization of Closure Not Allowed

Fatal error: Uncaught Exception: Serialization of 'Closure' is not allowed

You cannot serialize PHP closures with serialize() or store them in sessions. Extract the closure's logic into a named function or class, or use a library like opis/closure.

Maximum Function Nesting Level Reached

Fatal error: Maximum function nesting level of '256' reached, aborting!

Your code has infinite or excessively deep recursion. Add a proper base case to your recursive function or convert the recursion to an iterative approach.

Unexpected Behavior from foreach Reference

Last array element is unexpectedly duplicated after foreach with reference

After a foreach loop using &$value, the reference variable still points to the last array element. Unset the reference after the loop or avoid using references.

DateTime Unexpected Mutation

DateTime object unexpectedly modified when passed to a function

DateTime objects are mutable. Use DateTimeImmutable instead to prevent unintended modifications when passing dates to functions.

password_hash Returns False

password_hash() returns false or password_verify() always returns false

password_hash failed or the stored hash is truncated. Ensure the database column is at least VARCHAR(255) and that you are not modifying the hash before storing it.

Composer Autoload File Not Found

Warning: require(/app/vendor/autoload.php): Failed to open stream: No such file or directory

The Composer autoload file is missing. Run composer install to install dependencies and generate the autoloader.

Null Byte in Path

Fatal error: Uncaught ValueError: Path must not contain any null bytes

A file path contains a null byte character, likely from unsanitized user input. Validate and sanitize all user input used in file paths.

Unexpected Loose Comparison Result

Unexpected behavior: 0 == 'string' returns true in PHP 7

PHP's loose comparison operator == performs type juggling that can produce unexpected results. Use strict comparison === to compare both value and type.

Trait Method Collision

Fatal error: Trait method App\Trait\Timestampable::createdAt has not been applied as there are collisions with other trait methods on App\Entity\User

Two traits define a method with the same name. Use the insteadof operator to resolve the conflict and optionally alias one of the methods.

Cannot Return Value from Generator

Fatal error: Generators cannot return values using "return" in PHP 5.x

In PHP versions before 7.0, generators cannot use return with a value. Either upgrade to PHP 7+ or yield the final value instead.

preg_match Compilation Failed

Warning: preg_match(): Compilation failed: unrecognized character after (? at offset 5

Your regular expression has invalid syntax. Check for unescaped special characters, invalid modifiers, or unsupported syntax in the pattern.

PREG_BACKTRACK_LIMIT_ERROR

preg_match() returns false with preg_last_error() === PREG_BACKTRACK_LIMIT_ERROR

Your regular expression caused excessive backtracking. Simplify the pattern, use atomic groups or possessive quantifiers, or increase the backtrack limit.

Upload Max Filesize Exceeded

PHP Warning: POST Content-Length exceeds the limit / UPLOAD_ERR_INI_SIZE

The uploaded file exceeds the size limit configured in php.ini. Increase upload_max_filesize and post_max_size, or validate file size on the client side before uploading.

Timezone Not Set

Warning: date(): It is not safe to rely on the system's timezone settings

PHP's default timezone is not set. Set it in php.ini with date.timezone or in your code with date_default_timezone_set().

Illegal String Offset

Warning: Illegal string offset 'name'

You are using a string key to access a character in a string, but PHP expected an integer offset. The variable is a string, not an array.

mb_string Encoding Error

Warning: mb_convert_encoding(): Unable to detect character encoding

The multibyte string function cannot detect the encoding of the input. Specify the source encoding explicitly instead of relying on auto-detection.

Script Hangs from Infinite Loop

Script appears to hang or produces no output (infinite loop)

Your script contains an infinite loop where the exit condition is never met. Check loop conditions, counter increments, and boolean flag updates.

Cross-Site Scripting (XSS) Output

User input rendered as HTML without escaping, executing malicious JavaScript

Always escape output with htmlspecialchars() before rendering user input in HTML. Never trust user input or echo it directly into HTML context.

SQL Injection Vulnerability

Database query contains unsanitized user input, allowing SQL injection attacks

Never concatenate user input into SQL queries. Always use PDO prepared statements with parameterized queries to prevent SQL injection.

Strict Types Type Coercion Failure

Fatal error: Uncaught TypeError: add(): Argument #1 ($a) must be of type int, string given

With declare(strict_types=1), PHP will not coerce types automatically. Ensure arguments match the declared types exactly, or cast them before passing.

array_push on Non-Array

Fatal error: Uncaught TypeError: array_push(): Argument #1 ($array) must be of type array, null given

You are calling array_push() on a variable that is null instead of an array. Initialize the variable as an empty array before pushing to it.

Method Chaining Returns Null

Fatal error: Uncaught Error: Call to a member function where() on null

A method in your chain returned null instead of the expected object. Check that each method in the chain returns $this or the expected object for chaining to work.

json_encode Recursion Detected

Warning: json_encode(): Recursion detected / JSON_ERROR_RECURSION

The data structure you are trying to encode as JSON contains circular references. Remove the circular reference or implement JsonSerializable to control the serialization.

Cannot Access Protected Property

Fatal error: Uncaught Error: Cannot access protected property App\Entity\User::$password

You are trying to access a protected property from outside the class hierarchy. Use a public getter method or change the visibility.

PSR-4 Autoload Namespace Mismatch

Class 'App\Controller\HomeController' not found despite file existing at src/Controller/HomeController.php

The namespace in the class file does not match the PSR-4 autoload mapping in composer.json. Verify the namespace declaration matches the directory structure and autoload configuration.

utf8_encode/utf8_decode Deprecated

Deprecated: Function utf8_encode() is deprecated since PHP 8.2

utf8_encode() and utf8_decode() are deprecated in PHP 8.2 because they only handle Latin-1 encoding. Use mb_convert_encoding() with explicit encoding parameters instead.

Bugsly catches PHP errors automatically

AI-powered error tracking that explains what went wrong and suggests fixes. Set up in 2 minutes.

Get Started Free