0

I am trying to do the following:

Open a file, say "myfile.json" from a php- let's call it "utils.php"; Use it in other php pages; close it from another php.

I have tried to include "utils.php" in the other files and write in the utils file, but it does not seem to work. I suppose this happens because utils.php is never actually executed, only included, but if I should execute it, how can I do it without having to refresh any page, preferably right when the user gets on the main page? This should not be seen by the user, what he sees should remain the main page.

Thanks in advance, I am quite new to php, and am trying to learn.

4

1 回答 1

1

包含文件时,您正在运行其中的所有代码。函数和类不会被评估,但会被定义以备将来使用。如果您以此示例打开文件:

util.php

    <?php 

    $file_hand = fopen('/tmp/file.txt','r');

如果操作完成,您将有一个句柄。但是,变量 $file_hand 是全局的。如果你需要使用一个函数来关闭它,你需要下面的代码来完成它:

other.php
function close_file(){
    global $file_hand;
    fclose($file_hand)
}

或者您可以将句柄作为参数传递,例如:

function close_file($file_hand){
    fclose($file_hand)
}

不管你如何关闭文件。您必须确保您使用的变量与在 utils.php 中创建的变量相同。如果你这样关闭:

function close_file(){
    fclose($file_hand)
}

您在 until.php 文件中创建的变量与这个不同。

于 2013-04-30T19:52:16.560 回答