简体   繁体   中英

Ways to access elements of an array that's within an object

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM