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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?