繁体   English   中英

在另一个PHP文档中获取变量集

[英]Get Variable Set in Another PHP Document

好吧,所以我试图在我的index.php上调用一个函数,该函数将调用misc.php上的一个函数集。 misc.php上的函数使用在auction-loop.php上设置的数组,但它返回的好像变量未定义。

这是我的auction-loop.php的样子,

<?php
$auctions = array();
$row = array();
$sqlquery = "SELECT * FROM auctions";
if ($result = $db->query($sqlquery)) {
    while ($row = $result->fetch_assoc()) {
        $auctions[$row['id']]['id'] = $row['id'];
        $auctions[$row['id']]['title'] = $row['title'];
        $auctions[$row['id']]['featured_image'] = $row['featured_image'];
        $auctions[$row['id']]['description'] = $row['description'];
        $auctions[$row['id']]['date'] = $row['date'];
        $auctions[$row['id']]['location'] = $row['location'];
        $auctions[$row['id']]['highlights'] = $row['highlights'];
        $auctions[$row['id']]['catagories'] = $row['catagories'];
        $auctions[$row['id']]['notes'] = $row['notes'];
        $auctions[$row['id']]['terms'] = $row['terms'];
        $auctions[$row['id']]['contact'] = $row['contact'];
    }
}
?>

这是misc.php,

<?php
function auction_title($auction_id){
    echo $auctions[$auction_id]['title'];
}
?>

最后,在index.php上调用该函数,

include_once ('parts/connections/connection.php'); 
include_once ('parts/staticfiles/auction-loop.php');
include_once ('parts/staticfiles/misc.php'); 
<?php auction_title(1); ?>

有了这些,它就会散发出错误,

注意:未定义的变量:第8行的D:\\ xampp \\ htdocs \\ parts \\ staticfiles \\ misc.php中的拍卖

是不是在auction-loop.php上设置的数组没有使其变为其他。 提前致谢! :)

您没有将$ auction变量发送给auction_title()函数。 如果您希望生活在2005年,可以将global $ auctions放入auction_title()函数中。 或者,一种更好的处理方法是重新定义函数以接受两个参数。

function auction_title($auctions=array(),$auction_id=0){

    if (!empty($auctions) && isset($auctions[$auction_id])){
       return $auctions[$auction_id]['title'];
    }

} 

希望能有所帮助。

您必须告诉function auction_title ,它将使用global $auctions变量。

function auction_title($auction_id) {
  global $auctions;
  echo $auctions[$auction_id]['title'];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM