开发者

php variable variables and array or straight code?

I am using code igniter.

I have quite a large list of items being sent through post, some will be set, some wont be.

I have two ways of approaching the same problem.

/*DYNAMIC CODING */

$fields = array(
  'field1', 'field2',
  'field3', 'field4',
  'field5', 'field6',
  'fiel'... ...);

foreach($fields as $f)
  $$f = $this->input->post($f);

/* OR LITERAL CODING? */

  $field1 = $this->input->post('field1');
  $field2 = $this->input->post('field2');
  $field3 = $this->input->post('field3');
  $field4 = $this->input->post('field开发者_如何学Go4');
  $field5 = $this->input->post('field5');
  $field6 = $this->input->post('field6');
  $field7 = $this->...

Both methods will work, my question is, is there any reason to use one over the other?


Use dynamic coding in my experience, because it is my personal preference.

If your preference is either or the other, then use whatever you feel comfortable with, if you are coding with a means of someone else editing the code, whatever you choose make sure you add;

// a comment

to explain your code. Using either will differ in process time by a minimal unnoticeable amount of milliseconds, but understanding your code and commenting it correctly will save you alot more than milliseconds in the long run!


the literal coding might work better when getting variable autocomplete to work in your IDE, if you use one (like eclipse for example)

otherwise, whatever style you prefer


Literal coding may have a small performance benefit (as the dynamic code is first generating an array and then looping over it.)

But to me, the dynamic code is a lot more like how we talk and think. You don't say "Today I went to the grocery store and then I went to the bowling alley and then I went to my friend's house", you say "Today I went to the grocery store, bowling alley and my friend's house." Besides, dynamic code it's a lot less verbose which decreases the silly need to review over lots of lines of code (with the array, you know what's going to be in it once you see a pattern), you can instantly see what's going on, and it just looks better.

Yet it really depends on how you code. Some will completely disagree with what I say, and some will agree. If you can breathe a little easier seeing long repetitive lines, go for it. But whatever you do, don't forget THE most important coding-best practice: Comments.


You should use the first option, with an array of values and a loop, simply because those variables will probably change sometime in the future and updating an array is a lot simpler than updating multiple lines of code.

I would also guess that you need to reference those field names somewhere else along the way as well.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜