3.5.3.1.1 set

set(string $var, mixed $value)
  1. set(string $var, mixed $value)

set() 方法是从你的控制器向视图传输数据的主要方法.一旦你使用了set(),变量就可以在你的视图中访问了.

<?php
    
//First you pass data from the controller:

$this->set('color', 'pink');

//Then, in the view, you can utilize the data:

You have selected <?php echo $color; ?> icing for the cake.

?>
  1. <?php
  2. //First you pass data from the controller:
  3. $this->set('color', 'pink');
  4. //Then, in the view, you can utilize the data:
  5. You have selected <?php echo $color; ?> icing for the cake.
  6. ?>

set()方法还可以携带一个数组作为它的第一个参数.这通常是向视图分配一组信息的快速的方法.但要注意的是,在它被分配给视图前,数组键的下划线会被替换掉, (‘underscored_key’ 将会变成‘underscoredKey’):

<?php
    
$data = array(
    'color' => 'pink',
    'type' => 'sugar',
    'base_price' => 23.95
);

//make $color, $type, and $basePrice 
//available to the view:

$this->set($data);  

?>
  1. <?php
  2. $data = array(
  3. 'color' => 'pink',
  4. 'type' => 'sugar',
  5. 'base_price' => 23.95
  6. );
  7. //make $color, $type, and $basePrice
  8. //available to the view:
  9. $this->set($data);
  10. ?>