passing function values to another function in same class

感情迁移 提交于 2019-12-23 02:32:59

问题


I want to pass function values to another function in the same class, like to store some values in a variable and then call this variable in another function in the same class.

Here is my Code

public function ven_coupon()
    {
        if ($_POST) {
            $number = $_POST['coupon'];
            $query = $this->front->ven_coupon($number);
            if (count($query) <= 0 ) {
                echo "Not Valid";
            }
            $payment = $this->cart->total();
            $dis = $query['discount'];
            $name = $query['username'];
            $number = $query['number'];
            $discount['discount'] = ($payment*$dis)/100;
            $discount['data'] = $dis;
            $this->load->view('checkout',$discount);
        }
    }

    public function addcart()
    {
        $ven = $this->ven_coupon();
        echo $ven($name);
        echo $ven($dis);
        echo $ven($number);
    }

回答1:


You could create the fields(variables) you need outside the function then use them using the this keyword. For example:

private $dis;
private $name;
private $number;

public function ven_coupon()
{
    if ($_POST) {
        $number = $_POST['coupon'];
        $query = $this->front->ven_coupon($number);
        if (count($query) <= 0 ) {
            echo "Not Valid";
        }
        $payment = $this->cart->total();
        $this->dis = $query['discount'];
        $this->name = $query['username'];
        $this->number = $query['number'];
        $discount['discount'] = ($payment*$dis)/100;
        $discount['data'] = $dis;
        $this->load->view('checkout',$discount);
    }
}


public function addcart()
{
    $ven = $this->ven_coupon();
    echo $this->name;
    echo $this->dis;
    echo $this->number;
}



回答2:


Scope of variable is inside the function. You need to made variable as a part of class as:

Basic Example:

class yourClass{
   private $name;

   public function functionA(){
      $this->name = "devpro"; // set property
   }

   public function functionB(){
      self::functionA();
      echo $this->name; // call property
   }
}



回答3:


your function ven_coupon() doesn't return anything, therefore $ven is empty when you read it in your function addcart().

in order to pass several variables from one function to another, you need to create an array.

function ven_coupon(){
   $dis = $query['discount'];
   $name = $query['username'];
   $data=array('dis'=>$dis,'name'=>$name)
   return $data
}
function addcart()
{
    $ven = $this->ven_coupon();
    echo $ven['name'];
    //etc.
}

Edit: as you are already using an array $query you could simply return $query; in function ven_coupon and then read it in your function addcart()



来源:https://stackoverflow.com/questions/35831809/passing-function-values-to-another-function-in-same-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!