在头文件中定义PHP常量不起作用


Defining PHP constants in header file doesnt work?

我试图在config.php文件中定义常量。它的主要用途只是配置,我相信你已经猜到了。但它不起作用。这是我的config.php文件:

<?php
    define("KPEREQUEST", "0", true);
    define("KPERESPONSE", "1", true);
    define("KPEGET", 0, true);
    define("KPEPOST", 1, true);
?>

这是当我包含config.php并打印define kPAPost:时的结果

KPEPOST: ""

但如果我在index.php中定义常量,并从index.php中打印它们,结果如下:

KPEPOST: "1"

**编辑**

这是我的index.php文件:

<?php
    $title = "API Documents";
    include 'header.php';
    include "config.inc.php";
    echo "KPEPOST: '"" . KPEPOST . "'""; 
?>
<?php include 'footer.php'; ?>

我已经在wordpress、magento等网站上看到了一百万次。我不知道为什么这不起作用,我做了大量的研究来找出它,但我现在已经走到了死胡同。如有任何帮助,我们将不胜感激。为什么我不能在配置文件中定义常量,并在包含配置文件的文件中使用define?

听起来您的include路径中没有config.php(或config.php的特定副本)。

建议

  1. 为整个web应用程序定义根index.php
  2. 这样做:

    define('BASE_DIR', realpath(__FILE__));
    
  3. 然后你可以这样做:

    require_once BASE_DIR.'config.php';
    

进一步阅读

  • 如何有效地包含config.php
  • http://php.net/manual/en/ini.core.php#ini.include-路径

另一种可能的解决方案是使用。/在include过程中位于文件名前面。我无意中发现了它。

define("kPEPost", "1");

包括:

include("./header");
include("./includes/config.inc.php");