如何使用包含在一个函数内?

Mah*_*hks 16 php function include

我有一个大功能,我希望只在需要时加载.所以我假设使用include是要走的路.但我需要几个支持函数 - 只在go_do_it()中使用.

如果它们在包含的文件中,我会收到重新声明错误.见例A.

如果我将支持函数放在include_once中它可以正常工作,请参见示例B.

如果我使用include_once作为func_1代码,则第二次调用失败.

我很困惑为什么include_once导致函数在第二次调用时失败,它似乎没有第二次"看到"代码但是如果存在嵌套函数,它确实"看到"它们.

例A:

<?php
/*  main.php    */
go_do_it();
go_do_it();
function go_do_it(){
    include 'func_1.php';
}
?>

<?php
/*  func_1.php  */
echo '<br>Doing it';
nested_func()

function nested_func(){
    echo ' in nest';
}
?>
Run Code Online (Sandbox Code Playgroud)

例B:

<?php
/*  main.php    */
go_do_it();
go_do_it();
function go_do_it(){
    include_once 'func_2.php';
    include 'func_1.php';
}
?>

<?php
/*  func_1.php  */
echo '<br> - doing it';
nested_func();
?>

<?php
/*  func_2.php  */
function nested_func(){
    echo ' in nest';
}
?>
Run Code Online (Sandbox Code Playgroud)

cle*_*tus 20

include()在函数中使用的问题是:

include 'file1.php';

function include2() {
  include 'file2.php';
}
Run Code Online (Sandbox Code Playgroud)

file1.php将具有全球范围.file2.php范围是函数的本地范围include2.

现在所有函数都是全局的,但变量不是.我对此并不感到惊讶include_once.如果你真的想这样 - 老实说我不会 - 你可能需要借用旧的C/C++预处理器技巧:

if (!defined(FILE1_PHP)) {
  define(FILE1_PHP, true);

  // code here
}
Run Code Online (Sandbox Code Playgroud)

如果你想采用延迟加载的方式(顺便说一句可能有操作码缓存问题),请使用自动加载.


mea*_*gar 16

我有一个大功能,我希望只在需要时加载.所以我假设使用include是要走的路.

你的基本假设是错误的.这种优化会适得其反; 即使你的函数长达数百行,将它隐藏在PHP的解析器中也没有明显的好处.PHP解析文件的成本可以忽略不计; 真正明显的速度增益来自于找到更好的算法或更好的方式与您的数据库交谈.

也就是说,您应该在包含的文件中包含函数定义.而不是将函数体移动到func_1.php,将整个函数移动到文件中.然后require_once,您可以在需要它的每个文件中包含该函数的文件,并确保它只包含一次,无论您尝试包含它多少次.

一个例子:

file1.php

function test() {

}
Run Code Online (Sandbox Code Playgroud)

的index.php

require_once('file1.php');

include('table_of_contents.php');
test();
Run Code Online (Sandbox Code Playgroud)