/    Sign up×
Community /Pin to ProfileBookmark

function to read global var?

I’m sure this is dead easy, but how can I call a script-wide var from within a function? Is it something you do when defining the var, or is it a method of calling from within the function?

i.e.

$var = “poo”;
function test() {
echo $var; //outputs ‘poo’
}

Thanks in advance.

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@scragarDec 13.2004 — I don't understand the question.

[code=php]$var = "poo";
function test() {
echo $var; //outputs 'poo'
};[/code]

works fine, I asume you mean how to get this to work:

[code=php]function foo() {
$var = "test";
};
foo();
echo $var; // calls an error, $var is undefined.[/code]


in this example we just set $var to be global.

[code=php]function foo() {
global $var;
$var = "test";
};
foo();
echo $var; // no more errors, $var is now a global variable.[/code]
Copy linkTweet thisAlerts:
@NogDogDec 13.2004 — I believe it's:
[code=php]
function test() {
global $var;
echo $var; //outputs 'poo'
}

$var = "poo";
test();
[/code]

However, it's usually better for clarity and ease of maintenance to forego globals and instead make it a function parameter:
[code=php]
function test($myVar) {
echo $myVar;
}

$var = "poo";
test($var); //outputs 'poo'
[/code]
Copy linkTweet thisAlerts:
@mityaauthorDec 13.2004 — Yeah I'm trying to avoid feeding every var to the function, it's messy. In javascript, inside functions you can call vars specified outside the function in a totally different area of the script.

So if I specify $var at the top of my script, and then want a function be able to read it without it being fed to it, that's what I'm after.

Thanks for the help guys.
×

Success!

Help @mitya spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...