1

How can i pass multiple variables to a function?

For example, i want to pass variables from my controller to my view.

i want to pass var1, var2, and var3 by calling render() and i want it to go into my $vars array. how can i do that?

here is my code:

$var1 = "hi";
$var2 = "hello";
$var3 = "lol";

$this->render();

and here is my render() function:

$vars = array();

public function render($vars) {
        require dirname(__DIR__).'/views/header.php';
        require dirname(__DIR__).'/views/body.php';
        require dirname(__DIR__).'/views/footer.php';
    }
1
  • What exactly you want to do . "pass multiple variables to a function" and "i want to pass variables from my controller to my view" are 2 different things Commented Nov 18, 2016 at 5:00

2 Answers 2

2

Check this way, First assigned var 1, 2, 3 to vars array, then assign the vars array to render function

$var1 = "hi";
$var2 = "hello";
$var3 = "lol";

$vars = array($var1, $var2, $var3);

$this->render($vars);

public function render($vars) {
    print_r($vars);
    // loop values
    foreach($vars as $var){
        echo $var;
    }
    // or access one by one
    echo $vars[0];
    echo $vars[1];
    echo $vars[2];
}
Sign up to request clarification or add additional context in comments.

2 Comments

how can i access $vars[0] by just doing $var1?
@pixie123 as i understand your question, this is a numeric array, then array index(keys 0,1,2) assigned automatically, first assigned element starts at 0.
1

Create an instance for your view file and use predefined method of a controller file to set variables. Like this way:

return new ViewModel(array(
        'order_by' => $order_by,
        'order' => $order,
        'page' => $page,
        'paginator' => $paginator,
    ));

Since i am using Zend Framework-2. So it is basic syntax to send multiple variables to view file. and you can access these vars by using array keys.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.