开发者

How do i fill an objects attributes dynamically?

I am trying to save an object with a variable amount of "cols". The number of cols is equal to the number of headers. This is how the code looked before:

if(isset($_POST['submit'])){
    $sub = new Sub();
    $sub->product_id = $_POST['product_id'];

    $sub->col1 = $_POST['col1'];
    $sub->col2 = $_POST['col2'];
    $sub->col3 = $_POST['col3'];
    $sub->col4 = $_POST['col4'];
    $sub->col5 = $_POST['col5'];
    $sub->col6 = $_POST['col6'];
    $sub->col7 = $_POST['col7'];
    $sub->col8 = $_POST['col8'];
    $sub->col9 = $_POST['col9'];
    $sub->col10 = $_POST['col10'];
    $sub->col11 = $_POST['col11'];
    $sub->col12 = $_POST['col12'];
    $sub->col13 = $_POST['col13'];
    $sub->col14 = $_POST['col14'];
    $sub->col15 = $_POST['col15'];

This is how I want it to look:

if(isset($_POST['submit'])){
    $sub = new Sub();
    $sub->product_id = $_POST['product_id'];
    $i = 0;
    foreach($headers as $开发者_开发问答header){
        $i++ ;
        $sub->col.$i = $_POST['col'.$i];
    }

How do I pass the variable $i into the object's attributes? $sub->(col.$i) ? $sub->(col{$i}) ? Please help me figure this out =) Thank you


Try this:

$sub = new Sub();
$sub->product_id = $_POST['product_id'];
for($i = 1; $i <= count($headers); ++$i)
   $sub->{'col' . $i} = $_POST['col' . $i];

But, this is really not the way that the columns should be stored in the Sub object, you should use an array:

$sub->columns = array();
for($i = 1; $i <= count($headers); ++$i) {
    $sub->columns[] = $_POST['col' . $i];
}


You have to use {} :

$sub->{'col' . $i} = ...


$field = "col$i";
$sub->$field = "whatver"


I'd prefer a setter method.

class Sub {

  public function set($attribute, $value) {
    $this->$attribute = $value;
  }

}

Now you can do:

foreach($_POST as $key => $value) {
  $sub->set($key, $value)
}

Or without the loose coupling:

$i = 1;
while($value = $_POST['col' . $i]) {
  $sub->set('col' . $i, $value);
  $i++;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜