CakePHP 对一起使用 set() 和 compact() 的说明.仅适用于 compact() [英] CakePHP clarification on using set() and compact() together. Will only work w/ compact()
问题描述
我知道 compact() 是一个标准的 php 函数.而 set() 是蛋糕专用的方法.
I know compact() is a standard php function. And set() is a cake-specific method.
我正在运行一个简单的测试,将值传递给使用 ajax 生成的视图(我的控制器中的用户 render()),如果我的设置如下,它只会将值从控制器传递给视图:
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'));
通过阅读手册,set() 似乎应该在没有紧凑的情况下工作.
From reading the manual, it appears set() should work along w/out compact.
谁能解释为什么 set() 不能单独工作?喜欢
Can anyone explain why set() will not work alone? Like
$this->set('variable_name_to_pass');
推荐答案
根据CakePHP API:
参数:
混合 $one
需要
一个字符串或一个数据数组.
A string or an array of data.
混合 $two
可选 NULL
值如果 $one
是一个字符串(然后用作键).如果 $one
是 关联数组,则未使用,否则用作 $one
键的值.
Value in case $one
is a string (which then works as the key). Unused if $one
is an associative array, otherwise serves as the values to $one
's keys.
compact
函数返回一个关联数组,该数组通过获取输入数组中指定的名称、将它们用作键、获取这些名称所引用的变量的值并将其作为值来构建.例如:
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:
$fred = 'Fred Flinstone';
$barney = 'Barney Rubble';
$names = compact('fred', 'barney');
// $names == array('fred' => 'Fred Flinstone', 'barney' => 'Barney Rubble')
因此,当您将 compact
与 set
结合使用时,您使用的是 set
函数的单参数形式,通过传递它键值对的关联数组.
So when you use compact
in conjunction with set
, you're using the single parameter form of the set
function, by passing it an associative array of key-value pairs.
如果你只想在视图上设置一个变量,并且你想使用单参数形式,你必须以同样的方式调用set
:
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:
$variable_to_pass = 'Fred';
$this->set(compact('variable_to_pass'));
否则,可以使用set
的二参数形式:
Otherwise, the two parameter form of set
can be used:
$variable_to_pass = 'Fred';
$this->set('variable_to_pass', $variable_to_pass);
两者都实现相同的目标.
Both achieve the same thing.
这篇关于CakePHP 对一起使用 set() 和 compact() 的说明.仅适用于 compact()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!