function parts($part) { $structure = 'http://' . $site_url . 'content/'; echo($tructure . $part . '.php'); }
This function uses a variable $site_url
that was defined at the top of this page, but this variable is not being passed into the function.
How do we get it to return in the function?
To access the global variable within a function, use the GLOBAL keyword before the variable. However, these variables can be directly accessed or used outside the function without any keyword. Therefore there is no need to use any keyword to access a global variable outside the function.
To access a variable outside a function in JavaScript make your variable accessible from outside the function. First, declare it outside the function, then use it inside the function. You can't access variables declared inside a function from outside a function.
Add second parameter
You need to pass additional parameter to your function:
function parts($site_url, $part) { $structure = 'http://' . $site_url . 'content/'; echo $structure . $part . '.php'; }
In case of closures
If you'd rather use closures then you can import variable to the current scope (the use
keyword):
$parts = function($part) use ($site_url) { $structure = 'http://' . $site_url . 'content/'; echo $structure . $part . '.php'; };
global
- a bad practice
This post is frequently read, so something needs to be clarified about global
. Using it is considered a bad practice (refer to this and this).
For the completeness sake here is the solution using global
:
function parts($part) { global $site_url; $structure = 'http://' . $site_url . 'content/'; echo($structure . $part . '.php'); }
It works because you have to tell interpreter that you want to use a global variable, now it thinks it's a local variable (within your function).
Suggested reading:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With