php PHP函数返回字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12296624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:17:31  来源:igfitidea点击:

PHP Function to return string

phpstringfunction

提问by TheBlackBenzKid

I am fairly new to PHP. I have a function which checks the cost of price. I want to return the variable from this function to be used globally:

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

?>

回答by Jon

You should simply store the return value in a variable:

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

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

The $deliveryPricevariable above is a differentvariable than the $deliveryPriceinside the function. The latter is not visible outside the function because of variable scope.

$deliveryPrice上述变量是一个不同的比可变$deliveryPrice的内部的功能。由于变量范围的原因,后者在函数外部不可见。

回答by Bgi

<?
function getDeliveryPrice($qew){
    if ($qew=="1"){
        $deliveryPrice="60";
    } else {
        $deliveryPrice="20";
    }
    return $deliveryPrice;                          
}

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

?>

回答by Mansoorkhan Cherupuzha

<?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

?>

回答by Peon

As some alrady said, try using classes for this.

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

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;
    }
}

Now, to use it, just initialize the class and do what you need:

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

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

echo $myClass->getDeliveryPrice();