Jump to content

[SOLVED] local variables in fucntions?


JREAM

Recommended Posts

Heya, i guess globals are bad i read a lot,

 

I got this:

 

$a=1;

$b=2;

function x(){}

function y(){}

function z(){}

 

how can I make $a available in function x-z? 

global $a = 1; // is this bad?

what about

define('var_a', '1'); // is this bad?

 

Any tips =) ??

 

I dunno if you can local_scope function, or if that would be an option.

How do most people do this?

Link to comment
https://forums.phpfreaks.com/topic/118218-solved-local-variables-in-fucntions/
Share on other sites

You could pass by REFERENCE, not VALUE also...  The & character allows you to pass an argument to a function by its reference (or where it is stored in memory on the servers ram) rather than a COPY of its value.

 

<?php
function today($arg)  {
  $day = "Tuesday";
  echo "It is $day inside the function";  //should see Tuesday
  }

$day = "Monday";
today($day);

echo "It is $day out side the function";  //should see Monday
?>

 

$day in the function is not the same as $day inside the function.  GLOBAL makes them the same but has some drawbacks.

 

<?php
function today(&$arg)  {
  $day = "Tuesday";
  echo "It is $day in the function";  //displays Tuesday
  }

$day = "Monday";
today($day);

echo "It is $day out side the function";  //also displays Tuesday
?>

 

In the 2nd piece of code, when $day was passed as an argument to the function, it was passed by its reference so any changes to the reference change its value whenever it is called.  When its not passed by reference, new memory space is allocated for $day inside the function so it becomes a copy of $day, not the original $day.  THink of it like a copier machine.  Photocopy a form, then fill it out.  The original doesnt change.

 

Probably read up on it here:

 

http://devzone.zend.com/node/view/id/637 under "Checking References"

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.