[Pmwiki-users] Dev Q3: Avoiding Problems With Variable Scope in Add-On Scripts

Jonathan Scott Duff duff
Tue Mar 30 07:56:25 CST 2004


On Tue, Mar 30, 2004 at 07:46:32PM -0800, Steven Leite wrote:
> What's the best way to initialize variable's in an add-on so they have
> limited scope.
>
> For example, if you have to add-ons scripts that have been included in
> your config.php, and both of the add-ons have a variable like "$temp"
> or "$Output" (not in the scope of a function, but declared as a
> user-definable variable at the top of the php file), how to keep them
> seperate from each other?

You could always decrease the chances of a collision by prefixing your
globally scoped variables with the name of the file in which they
appear or something.  (In fact, I've occasionally thought that PmWiki
should do something like this just to "claim ownership" of certain
variables and clearly define a "public interface".)

Is there a particular reason these variables aren't in a function?

> Also, in the case of an external file like: myaddon-config.php
>
> I'm thinking the only way to keep the scope local is to
> a) create the local variables inside of a function instead of at the
>    top of the php add-on script
> b) in the case of an external config file, load it from a function,
>    and not at the top of the php add-on.
>
> Am I correct in this thinking? Anyone have any better ideas?

AFAIK you're correct. PHP doesn't have the concept of anonymous
scopes (i.e., bare blocks) so to get a new scope you need to declare
a function.

Alternatively, you can use the object oriented features of PHP
to limit the scope of a variable to your object.  But then you need an
object where an object mayn't fit.

-Scott
-- 
Jonathan Scott Duff
duff at pobox.com



More information about the pmwiki-users mailing list