Reputation: 63
Can't seem to make this work.
I want to make the array below available to a second function but it always comes up empty
The main code is this:
function GenerateSitemap($params = array()) {
$array = extract(shortcode_atts(array(
'title' => 'Site map',
'id' => 'sitemap',
'depth' => 2
), $params));
global $array;
}
function secondfunction()
{
global $array;
print $title;
// this function throws an error and can't access the $title key from the first function
}
GenerateSitemap()
secondfunction()
I'd like to use the title, id or depth KEYS inside a second function. They just come up empty and throw an error
Upvotes: 1
Views: 407
Reputation: 45829
You need to declare the variable as global
before you use it inside the function, otherwise it will implicitly create a local variable.
function myFunc() {
global $myVar;
$myVar = 'Hello World';
}
myFunc();
print_r($myVar); // 'Hello World'
You don't actually have to declare it initially in the globalscope, you will not get a notice/warning/error, although it is obviously good practice to do so. (Although if good practice is the goal then you probably shouldn't be using global variables to begin with.)
Upvotes: 0
Reputation: 1213
"The scope of a variable is the context within which it is defined."
https://www.php.net/language.variables.scope.php
You need to define the variable (at least initially) outside the function:
$array = array();
function GenerateSitemap($params = array()) {
global $array;
$array = extract(shortcode_atts(array(
'title' => 'Site map',
'id' => 'sitemap',
'depth' => 2
), $params));
}
function SecondFunction() {
global $array;
...
}
Upvotes: 1