这是最好的方法,PHP常量在所有文件中都可以访问,但在一个文件中声明


Which is the best way to do this, PHP constant that is accessable in all files but declared in one file?

对于在所有文件中都可以访问但在一个文件中声明的PHP常量,哪种方法是最好的?

文件A.php

    const MAX_VIDEOS = 4;

可在以下位置访问:

B.php 文件

    $maxvideosplusone = MAX_VIDEOS + 1;

如果你对这个问题有一个面向对象的建议,那就更好了。

请记住,const关键字用于class。如果你想调用它,那么你需要执行MyClass::CONSTANT。如果使用过程方法,则需要使用define函数。例如:

define('MAX_VIDEOS', 4);

file A.php中,并在file B.php:中使用include

include('file A.php');

您只需在一个文件中定义变量,然后将其包含在任何其他文件中:

定义它的文件。(文件A.php)

<?php
    define('MAX_VIDEOS', 4);
?>

包含常量的文件(文件B.php)

<?php
    include_once("fileconstants.php");
    print MAX_VIDEOS + 1;
?>
define("MY_VAR", $value);

用法:

MY_VAR;

您可以像这样使用define():

define('MAX_VIDEOS', 4);

而且从PHP 5.3开始,您也可以在类之外使用const关键字。