Using local
on a variable means that its previous state needs to be pushed onto a stack somewhere and restored again when the local scope is exited. Using my
on a variable simply creates an entirely new variable that shadows the previous variable with the same name -- the previous one is entirely untouched, and does not need to be saved anywhere. It is simply lying in wait when the local scope is exited and it is visible again.
This pushing/popping to a stack takes resources; there's a lot of work under the hood to ensure that this works properly. (Consider cases such as an exception being thrown while in local scope, or a signal handler being executed. I'm sure you can think of more.)
Besides being more efficient, using my
is much more logical. As a programmer introducing a local variable $foo, you don't need to worry about the semantic reason for the previous version of $foo, what data might already be in it, or indeed if there was a $foo already created. If sometime down the road the earlier declaration of $foo is removed, your local $foo
code will break, but my $foo
will be perfectly happy. Be a good programmer and keep your code in well-encapsulated pieces, which means using lexical scoping as much as you can. It's quite possible to write a large application and never need variables of package/global scope at all, especially when you use well-designed OO classes.