dongsu1539 2012-05-20 18:44
浏览 50
已采纳

访问对象内数组元素的方法

I'm trying to convert our existing codebase to a more correct approach. Our existing codebase is written in HTML with PHP and Javascript code inserted all over the place (not in an un-ordered fashion, but not like it should be).

So I'm converting our current codebase to make use of classes, so properties and methods are the way to proceed. But I have a problem. I (ideally) want to reference one of my class members by their names instead of by index. Let me put this in a code sample.

This is the form class:

class form {
    public $name;
    public $fields;

    {constructor goes here...}

    public function addField($type, $name, $hint = null, $info = null) {
        $this->fields[] = new field($type, $name, $hint, $info);
    }
}

And this is the field class (which the form class calls when creating a new form field):

class field {
    public $name;
    public $type;
    public $values;

    public function __construct($name) {
        $this->name = $name;
        $this->fields = null;
    }

    public function addValue($value, $minimum = null, $maximum = null, $step = 1) {
        $this->values[] = new value($value, $minimum, $maximum, $step);
    }
}

So my code would look like this:

$form = new form("form1");
$form->addField(NUMBER, "number1");
$form->fields[0]->addValue(25, 1, 250, 1);

It actually works, but it's not what I want in the end. I would like to call each field by its designated name so I could write this instead:

$form = new form("form1");
$form->addField(NUMBER, "number1");
$form->fields['number1']->addValue(25, 1, 250, 1);

Or even:

$form->addField(NUMBER, "number1")->addValue(25, 1, 250, 1);

Is it possible?

  • 写回答

1条回答 默认 最新

  • dongpu2694 2012-05-20 18:49
    关注

    It looks like the fields are just an array within the form object. So instead of

     $this->fields[] = new field($type, $name, $hint, $info);
    

    Could you just do this?

     $this->fields[$name] = new field($type, $name, $hint, $info);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真