NYCPHP Meetup

NYPHP.org

Position of variable definitions [was: Re: [nycphp-talk] php script]

Allen Shaw ashaw at polymerdb.org
Mon Feb 25 11:36:56 EST 2008


David Krings wrote:
> Allen suggests to "define that variable just before it's used, not 
> necessarily at the top of your script". Allen or someone else, what is 
> the benefit of doing it that way? What happens when you need to know 
> which variables are used in a script? When you document the script and 
> have to note which variables are input and which ones are output? Or 
> if you know you used a variable, but do not know the name, how would 
> you find it?
This is a coding style that works for me, which I picked up from Steve 
McConell's book, /Code Complete: A Practical Handbook of Software 
Construction/.  I have no idea if that reference carries any weight with 
most folks, but I found some sense in the argument he presented for 
initializing variables as they are used, which is essentially that in 
maintaining the code it's helpful to be able to look up a few lines and 
confirm that the variable was initialized, edit the initialization, 
remove it, etc.  There's no "right way to do it," of course, but I do 
find this style to be very convenient and to lend itself to ease of 
maintenance. 

I'm not sure how often you actually need a list of all the variables 
used in a script.  For objects and functions you do need to know the 
properties, parameters, return values and such, sure.  Go ahead and 
document those clearly at the top, preferably using some standardized 
documentation method (phpDoc, doxygen, etc.).  But the temporary 
variables used within a function or method are usually only relevant in 
the lines where they're being used.  Document them where you use them, 
and save yourself the nightmare of keeping a single comprehensive 
doc-block up to date.
> Allen also wrote "Again, it totally depends on the logical flow of 
> your scripts". Why/when would the location of variable definitions 
> depend on the logical flow of the script?
If he needs to use that value in the beginning of his script, he'll have 
to define it there.  Where it's used is determined by how he wants the 
script to work.  I still recommend defining/initializing/documenting it 
as close as possible to the place it's used.

- Allen

-- 
Allen Shaw
slidePresenter (http://slides.sourceforge.net)




More information about the talk mailing list