Edward Z. Yang wrote:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1
Tim Starling wrote:
It is nice from a self-documentation standpoint to put var declarations at the top of your classes. But understand that a var declaration takes up time and space when the object is initialised. If you leave it out, that overhead can be deferred, and maybe skipped altogether.
I find this to be a very interesting viewpoint. How much time/space, exactly, is saved by moving variable declarations from the object declaration to, say, the constructor? I've always felt that the self-documentation ability derived from having explicit member variables is more important.
Nothing is saved by moving them to the constructor, in fact it'll probably be slower. The idea is to defer variable initialisation until the variable is required. The saving, assuming the variable is never required, is on the order of a microsecond plus 84 bytes. So unless there's a lot of objects or it's in a tight loop, we're in the realm of micro-optimisation, and other considerations, such as personal style, are probably going to take precedence.
I wouldn't recommend leaving the var out when there is a need to initialise it to something simple, and you would need to add an isset():
var $x = 1; ... $this->doStuff( $x );
versus
if ( !isset( $this->x ) ) { $this->x = 1; } $this->doStuff( $x );
The second one is slower.
But please don't forget my main point: an object is a hashtable, you can add and remove variables. Don't be such a stickler for self-documentation and the way things are "meant" to be done that you tie yourself in knots trying to avoid dynamic variable creation. You can always document with a comment instead.
-- Tim Starling