gpt4 book ai didi

PHP 使用包含内部函数

转载 作者:可可西里 更新时间:2023-11-01 12:29:18 24 4
gpt4 key购买 nike

我正在尝试创建一个可以按如下方式调用的函数,

view( 'archive', 'post.php' );

这个函数真正做的是这个。

include( 'view/archive/post.php' );

这样做的原因是,如果将来我将目录扩展为 view/archive/another_level/post.php 我不想在我的代码中返回所有地方并更改所有包括路径。

目前这就是我的函数,除了它似乎是在函数内部调用 include,而不是在调用函数时调用...

function view( $view, $file )
{
switch ( $view )
{
case 'archive' : $view = 'archive/temp'; break;
case 'single' : $view = 'single'; break;
}

include( TEMPLATEPATH . "/view/{$view}/{$file}" );
}

我怎样才能让这个函数正确地包含文件?

编辑:

没有显示错误。感谢@Ramesh 的错误检查代码 ini_set('display_errors','On') 我能够看到包含的文件中还有其他“未显示”的错误,这些错误似乎导致文件不显示...

最佳答案

那个用例是explicitly documented :

If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function. An exception to this rule are magic constants which are evaluated by the parser before the include occurs.

恕我直言,将基本路径保持不变(您似乎已经在某种程度上这样做了)或者甚至进行全站搜索和替换(这在任何像样的编辑器中都是 30 秒的任务)比重写要简单得多所有包含的文件都使用全局变量。

关于PHP 使用包含内部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10121211/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com