我将一个文件包含在我的其他php文件中:
include(dirname(__FILE__) . '/send_notification.php');
我包含的文件的代码看起来像这样:
<?php
echo "Here!";
if(false === function_exists('sendNotification')) {
function sendNotification() {
echo "I HATE THIS";
}
}
echo "There!"
?>
文件包含如下:
include_once(dirname(__FILE__) . '/send_notification.php');
echo "And Here!";
但是它只回显这个:
Here!There!
怎么回事?
您应该始终包装您的函数以检查它的存在,以防止在包含时出现问题。并从包含的文件中删除关闭PHP标记?>
,以防止行尾(EOL)词法问题。
send_notification.php
<?php
if (false === function_exists('sendNotification')) {
function sendNotification() {
echo "I HATE THIS";
}
}
index . php
<?php
require_once __DIR__ . '/send_notification.php';
sendNotification();
//...
你也应该只在函数/配置页面上使用include_once
或require_once
符号,以防止在使用时覆盖/重复变量值/函数。
try this
<?php
function sendNotification() {
return "I HATE THIS";
}
?>
echo sendNotification();