dongqu9972 2016-12-28 18:59
浏览 104
已采纳

包括包含另一个php文件的php文件?

My PhP files contain some long string constants and I'm trying to factor them out. So I created "my_string_constants.php" and used include in header.php. So far that works fine.

Now another file, page.php also requires the string constants and header.php. The scheme below tries to clarify these dependendies.

enter image description here

The string constants now seem available in my header only, not the rest of my page. I tried to resolve this by adding global ... to each string constant in string_constants.php. This resolved the error of "Unknown variable" but my string constants still seem unavailable to most of the page content.

What's the right way to get this working?

UPDATE

The issue's been solved. I should have used define(myString instead of $myString = .... By doing so, I need just one include in header.php and the constants will be available to page.php as well.

Thanks a million, you guys are great.

  • 写回答

3条回答 默认 最新

  • doulao1934 2016-12-28 19:24
    关注

    One thing you would want to do is distinguish a constant from a variable. Especially if other developers end up working on this, they will be confused by your terminology.

    For constants, you do not need to declare them as global and they are defined like so:

    define('MY_CONSTANT', 'Value');
    

    It seems to me that the constants file is acting as your site wide configuration file, so to me, it makes sense to have that on every page, regardless of whether header is used or not. I would normally create a bootstrap file for this purpose.

    bootstrap.php:

    <?php
    require_once(__DIR__ . '/constants.php');
    require_once(__DIR__ . '/database.php');
    require_once(__DIR__ . '/session.php');
    

    You get the point, then every accessible page needs to include this bootstrap file and then possibly the header.

    page.php:

    <?php
    require_once(__DIR__ . '/bootstrap/bootstrap.php');
    require_once(__DIR__ . '/header.php');
    ?>
    <h1>Page Title</h1>
    

    In header.php, since it requires these constants, you can handle this in two ways, either check that the constants are defined (meaning, bootstrap was included first) or just use another require_once to make sure that file was loaded.

    if (!defined('MY_CONSTANT')) exit('Bootstrap failure');
    

    or

    require_once(__DIR__ . '/bootstrap/constants.php');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站