调用另一个php文件中的php函数


Call a php function in another php file?

我需要在另一个文件example.php中从index.php调用一个函数。如果我使用include,它也会从index.php中获取所有html。我只想要函数的结果。有办法做到这一点吗?

                        $rs = odbc_exec($con, $sql);
                        if (!$rs) {
                            exit("There is an error in the SQL!");
                        }
                        $data[0] = array('D','CPU_Purchased_ghz');
                        $i = 1;

                        while($row = odbc_fetch_array($rs)) {
                        $data[$i] = array(
                            $row['D'],
                            $row['CPU_Purchased_ghz']
                        );
                        $i++; 
                        }

                    //odbc_close($con); // Closes the connection
                    $json = json_encode($data); // Generates the JSON, saves it in a variable
                    echo $json;

基本上,index.php中的这段代码从查询数据库的文件中获取信息,并将其编码为json。我不想回显,而是想创建一个函数来回显json,并在一个新文件中调用它,以便只在页面

上显示json

创建一个functions.php文件。将函数添加到该文件中,并将该文件包含在example.php文件

在调用函数之前包含文件。

参见以下示例:

index.php

<?php
function myFunction() { //function .
    return "FirstProgram"; //returns
}
?>

现在使用includehttp://php.net/include包括index.php,使其内容可在第二个文件中使用:

example.php

<?php
    include('index.php');
    echo myFunction();  //returns myFunction();
?>

index.php

function myFunction() {
    return "It works!";
}

example.php

include('index.php');
echo myFunction();