简体   繁体   中英

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

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

file A.php

    const MAX_VIDEOS = 4;

which is accessable in:

file B.php

    $maxvideosplusone = MAX_VIDEOS + 1;

if you have an object oriented suggestion to this problem even better.

Remember that the const keyword is meant for CLASS use. If you want to call it then you will need to do MyClass::CONSTANT. If you are using a procedural approach then you need to use the define function . For example:

define('MAX_VIDEOS', 4);

In file A.php and use an include in file B.php :

include('file A.php');

You can just define the variable in one file, then include it in any other files:

The file where it's defined. (file A.php)

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

The file including the constant (file B.php)

<?php
    include_once("fileconstants.php");

    print MAX_VIDEOS + 1;
?>

You can use define() like this:

define('MAX_VIDEOS', 4);

And since PHP 5.3 you can use the const keyword also outside of classes.

define("MY_VAR", $value);

用法:

MY_VAR;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM