CakePHP : Set More Than One Variable By One $this->set Method In Controller

Hello Friends, Currently I am working on one CakePHP project and learning so many new things of cakePHP and today while working on one section I learn one new thing in which we can set more than one variable in controller by using only one $this->set method. I wanted to set so many variables in my controller to use it so I have searched that how we can set more than one variable in controller by $this->set method and i found that we can do that by using compact() php method. compact() takes the array you pass into it and looks for variables of the same name as the elements in that array. It then spits out an array of key => value pairs.

So generally we use four set method to pass four variables like this

$user = "Ankur";
$foo= "Gandhi";
$temp= "CakePHP";
$test= "Freelancer";
$this->set('user', $user);
$this->set('foo', $foo);
$this->set('temp', $temp);
$this->set('test', $test);

As you see in above code that we are using 4 set method to set variables to use it in view, Now please check below code to see how we can do these all things in a single set method.


$user = "Ankur";
$foo= "Gandhi";
$temp= "CakePHP";
$test= "Freelancer";
$this->set(compact('user', 'foo', 'temp', 'test'));

You can see in above code that we used only one set method and compact method to set variables to use it in view.What compact will do in this? compact() takes the array you pass into it and looks for variables of the same name as the elements in that array.You must have your variables name same as you passed elements in compact. for example If your variable is $user=”Ankur”; than you have to pass user in compact to set it for view. If you will use any other variable name in compact than it will not work.

Subscribe to PHP Freelancer

Enter your email address: