PHP Function to return string

后端 未结 4 1876
天涯浪人
天涯浪人 2021-01-11 19:36

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:



        
相关标签:
4条回答
  • 2021-01-11 20:01

    You should simply store the return value in a variable:

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

    The $deliveryPrice variable above is a different variable than the $deliveryPrice inside the function. The latter is not visible outside the function because of variable scope.

    0 讨论(0)
  • 2021-01-11 20:10
    <?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
    
    ?>
    
    0 讨论(0)
  • 2021-01-11 20:15
    <?
    function getDeliveryPrice($qew){
        if ($qew=="1"){
            $deliveryPrice="60";
        } else {
            $deliveryPrice="20";
        }
        return $deliveryPrice;                          
    }
    
    $price = getDeliveryPrice(12);
    echo $price;
    
    ?>
    
    0 讨论(0)
  • 2021-01-11 20:27

    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();
    
    0 讨论(0)
提交回复
热议问题