[Wylug-help] PHP equiv of my or local variable

Smylers@stripey.com Smylers at stripey.com
Wed, 22 Jan 2003 11:58:52 -0500 (EST)


On Wed, 22 Jan 2003, Gary Stainburn wrote:

> is it possible to have local variables within blocks in php, as you
> can with perl?

No.  That's something that PHP simplified out, presumably to make laerning
PHP easier.

> I want $workdate and $workday in the following code snippet to be
> local to the block, and neither reference nor infect global $workdate
> and $workday - while still referencing globals $year, $month etc.

The only local blocks in PHP are functions.  If you are outside a function
then all variables are global, and there is no way of preventing
infection.

> In Perl I'd symply put 'my' before each of their definitions

There is no equivalent PHP declaration.

> if (!$day) {
>   $workdate=sprintf("%04d-%02d-01",$year,$month);
>   $workday=return_string("rddate",
>          "from roster_days where rddate >= '$workdate' limit 1");
>   if (substr($workday,0,7) == substr($workdate,0,7)) {
>     $day=substr($workday,8,2);
>   } else {
>     $day='01';
>   }
>   if ($year == $tyear && $month == $tmonth) {
>     if ($day < $tday) {
>       $day=$tday;
>     }
>   }
> }

You could achieve what you want by cutting and pasting all that code into
a function at the top.  Use a global statement to indicate which global
variables you wish to use (or, even better, pass them as parameters):

  global $year, $month, $etc;

All variables used inside function that haven't been delcared global are
local to that function.

Hope that helps, and good luck.

Smylers