10

我对 PHP 相当陌生。我有一个检查价格成本的功能。我想从此函数返回变量以供全局使用:

<?
function getDeliveryPrice($qew){
    if ($qew=="1"){
        $deliveryPrice="60";
    } else {
        $deliveryPrice="20";
    }
    return $deliveryPrice;                          
}
// Assuming these two next lines are on external pages..
getDeliveryPrice(12);
echo $deliveryPrice; // It should return 20

?>
4

4 回答 4

14

您应该简单地将返回值存储在一个变量中:

$deliveryPrice = getDeliveryPrice(12);
echo $deliveryPrice; // will print 20

$deliveryPrice上面的变量是与函数内部不同的变量$deliveryPrice。由于变量范围,后者在函数外部不可见。

于 2012-09-06T09:08:27.163 回答
3
<?
function getDeliveryPrice($qew){
    if ($qew=="1"){
        $deliveryPrice="60";
    } else {
        $deliveryPrice="20";
    }
    return $deliveryPrice;                          
}

$price = getDeliveryPrice(12);
echo $price;

?>
于 2012-09-06T09:09:19.720 回答
3
<?php
function getDeliveryPrice($qew){
   global $deliveryPrice;
    if ($qew=="1"){
        $deliveryPrice="60";
    } else {
        $deliveryPrice="20";
    }
    //return $deliveryPrice;                          
}
// Assuming these two next lines are on external pages..
getDeliveryPrice(12);
echo $deliveryPrice; // It should return 20

?>
于 2012-09-06T09:12:26.773 回答
2

正如一些人所说,尝试为此使用类。

class myClass
{
    private $delivery_price;

    public function setDeliveryPrice($qew = 0)
    {
        if ($qew == "1") {
            $this->delivery_price = "60";
        } else {
            $this->delivery_price = "20";
        }
    }

    public function getDeliveryPrice()
    {
        return $this->delivery_price;
    }
}

现在,要使用它,只需初始化类并执行您需要的操作:

$myClass = new myClass();
$myClass->setDeliveryPrice(1);

echo $myClass->getDeliveryPrice();
于 2012-09-06T09:23:44.233 回答