[ACCEPTED]-CakePHP clarification on using set() and compact() together. Will only work w/ compact()-set
According to the CakePHP API:
Parameters:
mixed
$one
requiredA 17 string or an array of data.
mixed
$two
optional NULLValue 16 in case
$one
is a string (which then works as 15 the key). Unused if$one
is an associative array, otherwise serves 14 as the values to$one
's keys.
The compact
function returns 13 an associative array, built by taking the 12 names specified in the input array, using 11 them as keys, and taking the values of the 10 variables referenced by those names and 9 making those the values. For example:
$fred = 'Fred Flinstone';
$barney = 'Barney Rubble';
$names = compact('fred', 'barney');
// $names == array('fred' => 'Fred Flinstone', 'barney' => 'Barney Rubble')
So 8 when you use compact
in conjunction with set
, you're 7 using the single parameter form of the set
function, by 6 passing it an associative array of key-value pairs.
If you 5 just have one variable you want to set on 4 the view, and you want to use the single 3 parameter form, you must invoke set
in the 2 same way:
$variable_to_pass = 'Fred';
$this->set(compact('variable_to_pass'));
Otherwise, the two parameter form 1 of set
can be used:
$variable_to_pass = 'Fred';
$this->set('variable_to_pass', $variable_to_pass);
Both achieve the same thing.
Compact returns an array. So, apparently 4 set is checking it's parameters and if it's 3 an array. It knows that it's from compact. If 2 not it expects another parameter, the value 1 of variable.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.