user3002114
user3002114

Reputation:

How to use a variable of a function in another function of same class -Codeigniter

I want to assign the value of $Id from firstFunction to the variable $temp in secondFunction.

public function firstFunction()
{
    $Id = $_POST['quizID_click'];
}


public function secondFunction()
{
    $temp = ------;
}

Please let me know how to access $Id in secondFunction

Upvotes: 0

Views: 4919

Answers (5)

killstreet
killstreet

Reputation: 1332

public function firstFunction()
{
    $Id = $_POST['quizID_click'];
    $this->seconFunction($id);
}


 public function secondFunction($id)
 {
     $temp = $id;
 }

This is how to pass variables among functions.

Upvotes: 0

Dale
Dale

Reputation: 10469

To expand on my comment, you could create your variable as a property of your class.. it's been a while since used CI so forgive me, classes are classes though :)

class whatever
{
    public $id;

    public function firstFunction($postData)
    {
         $this->id = $postData['quizID_click'];
    }

    public function secondFunction()
    {
        $temp = $this->id;
    }
}

Hope that gets you going

Upvotes: 2

reignsly
reignsly

Reputation: 502

Create a public variables of your class so that you can access the variables in all methods.

class myClass{
    public $id;

    public function first(){
        $this->id = $this->input->post('quizID_click');
    }

    public function second(){
        $id = $this->id;
    }
}

But that depends on what you are tying to accomplish? Please elaborate what you are trying to do.

Upvotes: 1

Ilanus
Ilanus

Reputation: 6928

If i understand correctly you want to pass only a variable inside the Controller functions, You can do it by throwing a flash like this:

    public function firstFunction()
    {
        $this->load->library('session');
        $Id = $_POST['quizID_click'];
        $this->session->set_flashdata('item', $Id);
    }


    public function secondFunction()
    {
        $myVar = $this->session->flashdata('item');
    }

Basically you temporary save the variable value as flashdata giving it a 'item' value 'item' can be anything. then the second controller looks for this flashdata and asigns it to $myVar

Upvotes: 1

Andrius
Andrius

Reputation: 5939

Functions create local variables which are destroyed when the function completed. To maintain the variable you need, you'll have to return it from the function and then assign it to a variable.

I can see that you are using classes, so you'll need to access the function like a method. This should work:

public function firstFunction()
{
    $Id = $_POST['quizID_click'];
    return $Id;
}


public function secondFunction()
{
    $temp = $this->firstFunction();
}

Upvotes: 1

Related Questions