【问题标题】:PHP Function to return stringPHP函数返回字符串
【发布时间】:2012-09-06 09:07:22
【问题描述】:

我对 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

?>

【问题讨论】:

  • @M1th 我希望在 cmets 上对 fanboy 口头禅有一些反对意见。
  • @TheBlackBenzKid:有:标记 cmets 以供版主注意。已经这样做了,一会儿就会消失。
  • @TheBlackBenzKid 标记它。
  • 谢谢。我已经标记了。当然,我问对了庄园,为什么 OMG 的态度如此新奇。
  • @TheBlackBenzKid 记住,这是互联网。对于每一个有礼貌、乐于助人和友好的人来说,都有数百个相反的人。 SO非常擅长清除我们不想要的人,但它有点像打地鼠:)

标签: php string function


【解决方案1】:

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

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

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

【讨论】:

  • 还值得一提的是,在比较中它可能会根据字符串值进行检查?
  • @Fluffeh:嗯...没有实际区别。我不会向初学者提及这一点。
  • 我能不能说returnAsGlobal $deliveryPrice;
  • @TheBlackBenzKid:有,但这是你可以使用的最糟糕的做法之一并且它只是“全局或没有” - 没有选项说“做这个如果调用代码不在全局范围内,则调用者可用。接受我的建议,不要去那里。该函数也有可能通过引用接受“输出参数”,但同样:这不是该功能的使用方式。
【解决方案2】:
<?
function getDeliveryPrice($qew){
    if ($qew=="1"){
        $deliveryPrice="60";
    } else {
        $deliveryPrice="20";
    }
    return $deliveryPrice;                          
}

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

?>

【讨论】:

  • 请在您的答案中添加一些解释,以便其他人可以从中学习
【解决方案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

?>

【讨论】:

  • sheri prajul :)
  • 请在您的答案中添加一些解释,以便其他人可以从中学习
【解决方案4】:

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

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();

【讨论】:

  • 请在您的答案中添加一些解释,以便其他人可以从中学习 - 在这里使用课程有什么意义?它解决了哪个问题?变量本身并没有通过 this 变成全局的
猜你喜欢
  • 2022-01-06
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-04
相关资源
最近更新 更多