Re: [Fwd: Re: [PHP] Please stop me from tearing my hair out.]
| From: | James Ausmus | Date: | Thu, 19 Jun 2008 17:53:58 +0000 |
| Subject: | Re: [Fwd: Re: [PHP] Please stop me from tearing my hair out.] | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-275634@lists.php.net to get a copy of this message | ||
On Thu, Jun 19, 2008 at 7:54 AM, Robert Cummings <robert@interjinn.com> wrote:
<snip>
> Ummm, yes it is :) Static variables have persistence beyond the function
> call and thus beyond the function scope itself.
Umm, no it's not. Static variables have persistence, but are scoped
just like normal variables -
http://us2.php.net/manual/en/language.variables.scope.php,
about 10%
down the page, under the header "Using static variables" - "A static
variable exists only in a local function scope, but it does not lose
its value when program execution leaves this scope."
Three simple ways to fix this:
1. Declare $con as a global
2. Return $con from the initialization function, and pass it in as a
parameter to all functions that need it
3. Put all these functions into a class, and make $con a member of the
class, so it could be referenced by $this->con
From the looks of your code, #3 is really your right answer, as it
appears you're trying to create a set of functions that are related,
and need to shared common data - you've got yourself an object...
Otherwise, if you don't want to go OOP, then go with #2, as #1 is the
most dirty way of fixing the problem. :)
HTH
-James
>
>> > ie. When you create it (ie when you connect to
>> > MySQL) you could stick it in the global scope. ie In
>> > your connection function, make this the first
>> > statement:
>> >
>> > global $con;
>
> Yes, you could do that... but ad-hoc shoving stuff into global space is
> poor style.
>
>> > Then you can do the same in other functions, or
>> > alternatively you can access it like so:
>> >
>> > $GLOBALS['con']
>
> Not that I like the current implementation, I merely followed what he
> was aiming for, but the implementation above works fine in practice (not
> withstanding any syntax bugs I may have left since it's untested).
>
> Cheers,
> Rob.
>
> --
> http://www.interjinn.com
> Application and Templating Framework for PHP
>
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>