2014-08-13 13:28
浏览 121

无法在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.

    打赏 评论

相关推荐 更多相似问题