/    Sign up×
Community /Pin to ProfileBookmark

[code=php]

//Global
$foo = “Here is a $fruit”;

function local($fruit)
{
global $foo
$result = “$foo”;
echo $result;

}

local(‘banana’);

[/code]

I would like “Banana” to display…

When I call the function the global $foo doesn’t get fruit set to “banana”
What do I do?

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@NogDogDec 11.2007 — Besides the fact that the logic is flawed, since you cannot store a variable within a string and have that variable somehow magically replaced in your function, it is generally best to avoid the use of global variables in functions due the way they closely couple the function to the rest of the code, plus can lead to maintenance nightmares down the road. It is better to pass all external values as function parameters, e.g.:
[code=php]
function example($text, $search, $replace)
{
echo str_replace($search, $replace, $text);
}
$text = "Here is a [[fruit]].";
example($text, '[[fruit]]', 'banana');
[/code]
×

Success!

Help @hdogg 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 5.18,
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: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

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

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...