duan0427 2011-07-25 05:07
浏览 89
已采纳

如何动态填充对象属性?

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

  • 写回答

4条回答 默认 最新

  • dongzha2525 2011-07-25 05:09
    关注

    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];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件