无法在php require文件中调用函数

时间:2014-08-13 13:28:36

标签: php function

我在这里错过了一些非常简单的东西!

index.php需要connect.php:

<?php require_once('scripts/connect.php'); ?>

connect.php从数据库收集一些数据并将其放在一个数组中:

<? $query = "SELECT id,termine FROM tbl_standorte";
$result = mysql_query($query) or die ("no query");
$result_array = array();
while($row = mysql_fetch_assoc($result)){$termine_array[] = $row;} ?>

index.php然后需要sub.php:

<? require('sub.php');?>

sub.php包含以下函数,然后通过将变量传递给$ value来调用:

<? function searchSubArray($value) {
        foreach ($termine_array as $subarray){  
        if (isset($subarray['id']) && $subarray['id'] == $value)
          echo 'Result:'.str_replace(';','&lt;br&gt;',$subarray['termine']);       
        }
} ?>

sub.php然后调用函数<p><? searchSubArray(133);?></p>

然而,我没有输出!我错过了什么?

1 个答案:

答案 0 :(得分:1)

简单的解决方案可能只是添加

global $termine_array;
在你的foreach声明之前

<? function searchSubArray($value) {
    global $termine_array;
    foreach ($termine_array as $subarray){  
    ...

但是,我强烈建议您考虑从头开始重写。首先,将已弃用的mysql_*函数的使用替换为mysqliPDO。然后,我看看你是否可以用对象替换全局变量的使用。也许有一个包含standorte.php函数的getAllIDs()类。

我建议调查一些MVC框架,因为你在这里的代码似乎真的可以使用它。 index.php正试图成为控制者,connect.php正试图成为模特,sub.php正试图成为一个视图。