I know compact() is a standard php function. And set() is a cake-specific method.
I am running a simple test of passing a value to a view generated with ajax (user render() in my controller), and it only passes the value from the controller to the view if my setup is like so:
$variable_name_to_pass = "Passing to the view using set() can compact()";
$this->set(compact('variable_name_to_pass'));
From reading the manual, it appears set() should work along w/out compact.
Can anyone explain why set() will not work alone? Like
$this->set('variable_name_to_pass');
According to the CakePHP API:
The
compact
function returns an associative array, built by taking the names specified in the input array, using them as keys, and taking the values of the variables referenced by those names and making those the values. For example:So when you use
compact
in conjunction withset
, you're using the single parameter form of theset
function, by passing it an associative array of key-value pairs.If you just have one variable you want to set on the view, and you want to use the single parameter form, you must invoke
set
in the same way:Otherwise, the two parameter form of
set
can be used:Both achieve the same thing.
compact returns an array. so apparently set is checking it's parameters and if it's an array, it knows that it's from compact. and if not it expects another parameter, the value of variable.