Hi,
Joachim Weiß wrote:[color=blue]
> Hi Mike,[color=green]
>> I am used to working with strongly typed languages. I am just trying to find
>> out what the scoping rules are for php.[/color]
>
> You nearly ansewered your question by yourself.
>
> Because the lack of typing variables are always in the function scope.
> In PHP all varibles are declared by default (AFAIK you may not rely on a
> value).[/color]
AFAICT this is not an issue if strong/weak typing, but of lexical scope
(more precisely, the lack of it). Variables could be as well typeless
but at the same being subject to lexical scoping, that is, the variable
exists only from where it is defined to the end of the code block that
contains its declaration, such as in Perl (see <http://tnx.nl/php#scope>
for a more detailed comparison).
[color=blue]
> echo("hello $x") will print "hello " and not yield an error like
> "undeclared variable x in line ...[/color]
Unless of course you have the interpreter configured to give you
"notices" on these events (setting E_NOTICE in error_reporting). They
don't stop or alter your script execution at all, but at least they give
you a warning that something *may* have gone wrong.
And in PHP5 there is E_STRICT which supposedly would abort the execution
if one of this notices is found. Sadly enough, you can't check for
strictness without attempting to actually _run_ the script :-(
[...]
[color=blue]
> However scope and and typing shouldn't be mixed up. The variable Scope
> in C is defined by the curly braces.
>
> The curly braces in PHP have only the grouping purpose of code and not
> the declaration purpose of C.[/color]
Yes, that's exactly the point.
[color=blue]
> Variables Scope in PHP is borderd by the keywords function, class.
>
> Apart of this, I always considered it as a bad idea to declare variables
> on another place but on the beginning of the function.[/color]
Well, I tend to declare them close to where they are going to be used
(loops, mostly), so the chunk of code sort of contains most of involved
stuff and can be understood at a glance. But that's a matter of taste,
of course :)
--
Cristian Gutierrez /*
crgutier@dcc.uchile.cl */
"Never put off until run time what you can do at compile time."
-- David Gries, in "Compiler Construction for Digital Computers",
circa 1969.