calling an function containing an array
Please look at my code:
function getShopConfig()
{
$sql = "SELECT sc_name, sc_address, sc_phone, sc_email, sc_shipping_cost, sc_order_email, cy_symbol, sc_currency
FROM kol_shop_config , kol_currency
WHERE sc_currency = cy_id";
$result = dbQuery($sql);
$row = dbFetchAssoc($result);
if ($row) {
//extract($row);
$shopConfig = array('name' => $row['sc_name'],
'address' => $row['sc_address'],
'phone' => $row['sc_phone'],
'email' => $row['sc_email'],
'sendOrderEmail' => $row['sc_order_email'],
'shippingCost' => $row['sc_shipping_cost'],
'currency' => $row['sc_currency']);
}
return $shopConfig;
}
then im calling it like,
<td colspan="4" align="right"><?php getShopConfig(); echo $shopConfig['name'];?></td>
but nothing is being displayed.. where is the mistake?? please help.
note: both are in the same page. dbQuery() and dbFetchAssoc() functions are pre-defined and has worked properly before. if i echo it inside the func开发者_如何学编程tion and then just call it then its working properly.
<?php
$shopConfig = getShopConfig();
echo $shopConfig['name'];
?>
You have to assign returned array to some ($shopConfig
) variable before.
<?php $shopConfig = getShopConfig(); ?>
<td colspan="4" align="right"><?php echo $shopConfig['name'];?></td>
You are only returning the value but not catching it in any variable.
Try
<?php $shopConfig=getShopConfig(); echo $shopConfig['name'];?>
Your function is returning a value. You must assign this value to a variable then then access the element you want from that variable: i.e.
<td colspan="4" align="right"><?php $configs = getShopConfig(); echo $configs['name'];?></td>
What you are trying to do is use the variable $shopConfig
which has been declared in the function. This is a local variable and does not exist outside the function. You can make a global $shopConfig
if you want, but that's a redundant solution since you are returning the array from function. You should avoid global variables as it makes your code more difficult to understand and maintain.
There is, however, a short-hand way of doing this (perhaps you are only using the function to get that element 'name'
) by accessing the return value directly: i.e.
<td colspan="4" align="right"><?php echo $getShopConfig()['name'];?></td>
精彩评论