PHP error guide

PHP Fatal Error: Cannot redeclare function

Error summary

The same function was defined twice—usually a file included multiple times without `include_once`/`require_once`, or a name collision with another library.

What it means

The same function was defined twice—usually a file included multiple times without include_once/require_once, or a name collision with another library.

What the error means

PHP function names are global (unless namespaced). A second function name() definition aborts request startup.

Why PHP produces it

Unlike class autoloading, plain function definitions execute when the file is loaded. Double inclusion re-runs the definition.

PHP version notes

Namespaced functions reduce global collisions; still cannot redeclare the same FQFN.

Most common causes

  • Using include/require instead of *_once for helpers
  • Two packages defining the same global function
  • Copy-pasted helper files both loaded

Minimal examples

BAD — reproduces the problem

php
include 'helpers.php';\ninclude 'helpers.php'; // Fatal: cannot redeclare

FIXED — safer pattern

php
require_once 'helpers.php';\nrequire_once 'helpers.php'; // no-op

Step-by-step diagnosis

  1. Read both paths in the fatal message (previous declaration vs current).
  2. Search the codebase for function <name>.
  3. Check Composer files that might load helpers twice.

Fixes

Fix #1: Use require_once

Load definition files once.

php
require_once __DIR__ . '/helpers.php';

Fix #2: Namespace or guard definitions

Prefer namespaced functions or function_exists guards for polyfills.

php
if (!function_exists('format_price')) {\n    function format_price(int $cents): string {\n        return number_format($cents / 100, 2);\n    }\n}

Common mistakes when fixing it

  • Wrapping entire files in function_exists incorrectly and hiding real duplicates

How to prevent it

  • Autoload classes instead of global function files when possible
  • Keep a single helpers entrypoint

Web server / environment notes

Common in legacy apps with shared helper includes

Tags: cli,fpm,wordpress

Categories

Relevant ZendStudio.net tools