douqiaoru2583 2014-08-13 13:28
浏览 138
已采纳

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

I'm missing something really simple here!

index.php requires connect.php:

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

connect.php collects some data from a DB and places it in an array:

<? $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 then requires sub.php:

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

And sub.php contains the following function which is then called by passing a variable to $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 then calls the function <p><? searchSubArray(133);?></p>

However, I get no output! What am I missing?

  • 写回答

1条回答 默认 最新

  • duanjunao9348 2014-08-13 14:02
    关注

    The simple solution is likely just adding

    global $termine_array;
    

    before your foreach statement as such

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

    However, I'd strongly recommend that you consider re-writing this from the ground up. Start by replacing your usage of the deprecated mysql_* functions with either mysqli or PDO. Then, I'd see if you can replace your use of global variables with objects. Maybe have a standorte.php class that contains a getAllIDs() function.

    I'd suggest looking into some MVC frameworks, as the code that you have here seems like it could really use it. index.php is trying to be a controller, connect.php is trying to be a model, and sub.php is trying to be a view.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退