如何传递动态变量?

时间:2012-11-27 10:13:04

标签: php

我对此的研究,找不到我想要的东西。

class headerStyle{
 // now  creating our CONSTRUCTOR function
 function __construct($args=array()) {
     $this->fields = array('background','color','fontSize','backgroundUrl','imagePosition','Width','Height','backgroundSize','margin','padding','backgroundRepeat');
      foreach ($this->fields as $field) {
                $this->{"$field"} = $args["$field"];
                 }
         }
}


$style = new headerStyle(
       array(
         background =>"#DEDEDC",
         color=>"#F5F3F4",
         fontSize=>"24px",
         backgroundUrl=>"_images/bodyBg1.jpg",
         backgroundSize=>"50% 50%",
         padding=>"10px 0px 0px 0px",
         margin=>"0px 0px 0px 0px",
         width=>"100%",
         height=>"60px",
         imagePosition=>"top-left",
            )
);

而不是给出一个值,我需要传递一个动态变量,如background => $ _ post ['headerBg'];

2 个答案:

答案 0 :(得分:2)

你快到了。可以使用$_POST['headerBg'];访问PHP中的POST数组(注意它是大写的)。

class headerStyle{
 // now  creating our CONSTRUCTOR function
 function __construct($args=array()) {
     $this->fields = array('background','color','fontSize','backgroundUrl','imagePosition','Width','Height','backgroundSize','margin','padding','backgroundRepeat');
      foreach ($this->fields as $field) {
                $this->{"$field"} = $args["$field"];
                 }
         }
}


$style = new headerStyle(
       array(
         background =>$_POST['headerBg'],
         color=>"#F5F3F4",
         fontSize=>"24px",
         backgroundUrl=>"_images/bodyBg1.jpg",
         backgroundSize=>"50% 50%",
         padding=>"10px 0px 0px 0px",
         margin=>"0px 0px 0px 0px",
         width=>"100%",
         height=>"60px",
         imagePosition=>"top-left",
            )
);

答案 1 :(得分:0)

你的数组设置错误,它有数字键,你想要一个关联数组。定义默认值,然后使用array_merge()覆盖设置的任何元素的默认值:

function __construct($args=array()) {
     $defaults = array('background' => '', 'color' => '', 'fontSize' => '', 'backgroundUrl' => '', 'imagePosition' => '', 'Width' => '', 'Height' => '', 'backgroundSize' => '', 'margin' => '', 'padding' => '', 'backgroundRepeat' => '');

     $this->fields = array_merge($defaults, $args);
}

可以通过对元素进行硬编码,或者从$_POST获取它来尝试使用:

$style = new headerStyle(
   array(
     background =>'',
     color=>"#F5F3F4",
     fontSize=>"24px")
);
相关问题