Jump to content

Something Global


xor83

Recommended Posts

This question may sound very lame...  :wtf: ... But I have never able to know how to define a variable that I can use in different functions in a same file. There is no class structure just a PHP file with some functions. Is it possible to use some type of variable that can be share by all functions and that variable should not be a session variable .

Something like:

 

<?php 
$my_global_var;

function A()
{
// use $my_global_var here
}

function B()
{
// use $my_global_var here and should retain the last value
}
?>

 

Something like in VB6.... :confused:

 

Thanks

Link to comment
Share on other sites

Please don't suggest using the global keyword. In the example you posted, what if I have more than just two variables in my application that I need to use with the function and want to reuse the function?

 

<?php
$a = 1;
$b = 2;

$w = 44;
$x = 184;
$y = 12;
$z = 13;
?>

 

^^^ I need to use the function to find what output it gives for $w and $x and for $y and $z. Writing the function using global, it is not a general purpose function and it can only operate on the data it was hard coded to work with. You would need to use more code to copy the $w and $x values to $a and $b, call the function, then copy $y and $z to $a and $b before you can call the function again.

 

Functions should aways be written to be general purpose and use parameters when there are called.

Link to comment
Share on other sites

In real applications, where you can have hundreds of functions, it creates more work and wastes time keeping track of all the variables you are passing into functions using the global keyword because you cannot duplicate any of the names between functions in order to prevent interference between the functions.

 

Using functions are supposed to make coding easier and take less time. Not more time. Don't use the global keyword.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.