PHP cannot redeclare function

I am making a contact form for my site, and it uses a database to store messages sent. I have written a function which adds the message, and the users email, however when I call it in addcontactmessage.php it tells me that I cannot redeclare the function.

Fatal error: Cannot redeclare add_message() (previously declared in C:Program Files (x86)EasyPHP-DevServer-14.1VC11datalocalwebprojectsPortfolio -- Websiteassetfunctions.php:3) in C:Program Files (x86)EasyPHP-DevServer-14.1VC11datalocalwebprojectsPortfolio -- Websiteassetfunctions.php on line 5

init.php:

<?php
require'connect.php';
require'functions.php';
?> 

addcontactmessage.php:

<?php

include'asset/init.php';

    $message = $_POST['message'];
    $email = $_POST['email'];

    add_message($message, $email);

    header('Location: index.php'); 
?>

functions.php:

<?php
    include 'init.php';
    function add_message ($message, $email) {
        mysqli_query($con, "INSERT INTO `contactmessage`(`message`, `email`) VALUES ('$message,'$email')");
    }
?>

The problem is you are including init.php twice. Once in addcontactmessage.php and again in functions.php.

I'd recommend removing the include 'init.php'; line from your functions.php page.

Or

You can use php's built in functions require_once and include_once to avoid loading the same file more than once.


An example

init.php:

<?php
require_once('connect.php';
require_once('functions.php');
?> 

addcontactmessage.php:

<?php

include_once('asset/init.php');

    $message = $_POST['message'];
    $email = $_POST['email'];

    add_message($message, $email);

    header('Location: index.php'); 
?>

functions.php:

<?php
    include_once('init.php');
    function add_message ($message, $email) {
        mysqli_query($con, "INSERT INTO `contactmessage`(`message`, `email`) VALUES ('$message,'$email')");
    }
?>

使用require_onceinclude_once来防止加载相同的包含文件两次。


Yup, was just about to suggest it. init.php is being included back inside of functions.php . Removing it from functions.php should work.

链接地址: http://www.djcxy.com/p/69536.html

上一篇: 解析错误:语法错误,意外的'[',期待

下一篇: PHP无法重新声明函数