繁体   English   中英

PHP require_once失败?

[英]PHP require_once fails?

因此,我正在尝试使用PHP构建模板加载器系统。 这是到目前为止我得到的:

config.php文件:

<?php
    $style_assets_path = "/includes/styles/";

    if ($_GET['page_id'] !== '1'){
        header('Location: /template.php?pageid=1');
        exit(0);
    }

    if ($_GET['page_id'] <= 100) {
        $template = "/main/main.php";
    }

    function loadTemplate() {
        require_once dirname(__FILE__) . "$style_assets_path" . "templates" . "$template";
        // This should output: /includes/styles/templates/main/main.php
    }
?>

home.php:

<?php
    require_once dirname(__FILE__) . "/config.php";
    loadTemplate($template);
?>

所以当我打开home.php时出现以下错误:

Warning: require_once(/home/xxxxxxx/public_htmltemplates/) [function.require-once]: failed to open stream: No such file or directory...

我究竟做错了什么?

函数与全局变量的作用域不同,除非将它们作为参数传递或使用global关键字(仅出于完整性考虑),否则无法访问它们。

如果尽管将它们声明为常量,但它们的值不会改变,则更漂亮:

declare('STYLE_ASSETS_PATH', "/includes/styles/");

if ($_GET['page_id'] !== '1'){
    header('Location: /template.php?pageid=1');
    exit(0);
}

if ($_GET['page_id'] <= 100) {
    $template = "/main/main.php";
}

loadTemplate($template);

function loadTemplate($template) {
    require_once dirname(__FILE__) . STYLE_ASSETS_PATH . "templates" . "$template";
}

这里正确的答案! 仔细查看您的错误消息! 这是因为, $ style_assets_path不是在函数中确定的。 您应该将这些变量设置为全局函数:

 function loadTemplate() {
        global $style_assets_path;
        global $template;
        require_once dirname(__FILE__) . "$style_assets_path" . "templates" . "$template";
        // This should output: /includes/styles/templates/main/main.php
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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