CakePHP澄清使用set()和compact()在一起。只会工作w / compact() [英] CakePHP clarification on using set() and compact() together. Will only work w/ compact()

查看:564
本文介绍了CakePHP澄清使用set()和compact()在一起。只会工作w / compact()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道compact()是一个标准的php函数。

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()应该与w / out紧凑。

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


参数:

Parameters:

mixed $ one 必需

字符串或数组数据。

混合 $ 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()在一起。只会工作w / compact()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆