1

I have a private function which has lots of variables, let's say these: $foo, $bar, $baz.

Inside the function, I call parent::_setViewVars(array('foo','bar','baz'));

This _setViewVars looks so:

protected function _setViewVars($a){
    foreach($a as $v){
        global $$v;
        $this->set($v, $$v);
    }
}

I just want to get rid off cakephp's shit like 80 lines of $this->set('selected_areas',$selected_areas);, that's what this function is for.

_setViewVars cannot access $$v, because it's not a global variable. Given that this function is being called from the context that has these variables, can I reach them somehow?

(by the way if there is a cakephp way of bulk setting view variables with the same names, tell me how -- I haven't found one)

PS: packing everything into an array is NOT a solution, we're talking about thousands of unneccessary square brackets here.

4
  • Take a look at compact, which creates array useful for your scenario. Commented Jun 28, 2014 at 17:02
  • I've tried it: compact also does not reach these variables. Commented Jun 28, 2014 at 17:10
  • Can you redefine parent::_setViewVars? Or skip calling it altogether in favor of your own loop in which you call ->set(), dealing with output of compact? Commented Jun 28, 2014 at 17:16
  • 1
    global? Seriously? Just use compact() in your controller actions (not in a redundant separate method): $this->set(compact('foo', 'bar', 'baz')); That's btw exactly what CakePHP does when baking controllers... Commented Jun 28, 2014 at 18:35

1 Answer 1

1

What you're looking for is actually pretty standard PHP:

compact() - Create array containing variables and their values

Example showing it's use in a CakePHP Action:

$var1 = "I";
$var2 = "love";
$var3 = "pizza!";
$this->set(compact('var1', 'var2', 'var3'));

(might want to try to tone down the hatred a bit - you're more likely to get help that way)

Sign up to request clarification or add additional context in comments.

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.