簡體   English   中英

如何使用包含在一個函數內?

[英]How to use include within a function?

我有一個大功能,我希望只在需要時加載。 所以我假設使用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';
}
?>

例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';
}
?>

在函數中使用include()的問題是:

include 'file1.php';

function include2() {
  include 'file2.php';
}

file1.php將具有全局范圍。 file2.php的作用域是函數include2本地。

現在所有函數都是全局的,但變量不是。 我對include_once混亂並不感到驚訝。 如果你真的想這樣 - 老實說我不會 - 你可能需要借用舊的C / C ++預處理器技巧:

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

  // code here
}

如果你想采用延遲加載的方式(順便說一句可能有操作碼緩存問題),請使用自動加載。

我有一個大功能,我希望只在需要時加載。 所以我假設使用include是要走的路。

你的基本假設是錯誤的。 這種優化會適得其反; 即使你的函數長達數百行,將它隱藏在PHP的解析器中也沒有明顯的好處。 PHP解析文件的成本可以忽略不計; 真正明顯的速度增益來自於找到更好的算法或更好的方式與您的數據庫交談。

也就是說,您應該在包含的文件中包含函數定義。 而不是將函數體移動到func_1.phpfunc_1.php整個函數移動到文件中。 然后,您可以在需要它的每個文件中require_once包含該函數的文件,並確保它只包含一次,無論您嘗試包含它多少次。

一個例子:

file1.php

function test() {

}

的index.php

require_once('file1.php');

include('table_of_contents.php');
test();

嗨,我解決了這個問題

//connect.php


$connect ="OK";

include "connect.php";

show($connect);

function show($connect){


echo $connect;


}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM