Domanda

I have the following line in a file named config.php:

$objects["settings"]["template"]["value"] = "yes";

Then a file named funcs.php which includes config.php, with the following lines.

echo $objects["settings"]["template"]["value"];
function testfunction() {
    echo "<br />function output: ".$objects["settings"]["template"]["value"];
}

I then have index.php which includes funcs.php, as follows.

require_once("funcs.php");
testfunction();

How come the output from the function doesn't read the variables and they are empty?

yes
function output:

The output im expecting is:

yes
function output: yes

Thanks in advance.

EDIT: I went with Yoda's answer as it was the most detailed answer regarding passing $objects as a parameter. Thanks to everyone else who answered!

È stato utile?

Soluzione 2

The variable is not in function scope. You can achieve that by using global keyword. However doing it like this is bad practice and you should rather pass the value to function through function parameter.

Use of global (bad practice):

$objects["settings"]["template"]["value"] = "yes";

function testfunction() {
    global $objects;        
    echo "<br />function output: ".$objects["settings"]["template"]["value"];
}

testfunction();

Passing value through function parameter:

$objects["settings"]["template"]["value"] = "yes";

function testfunction($objects) {   
    echo "<br />function output: ".$objects["settings"]["template"]["value"];
}

testfunction($objects);

Altri suggerimenti

Simply pass the object as parameter

function testfunction($objects) {
    echo "<br />function output: ".$objects["settings"]["template"]["value"];
}

The variable is outside the scope of the function. To make the variable available in the function, you have to pass is an argument into the function. You will also need to modify the function definition. See sample below

// function definition
function testFunction($variable) {
    echo $variable;
}

// call the function
$your_variable = "Some output";
testFunction($your_variable);

This should give you the expected behaviour.

Using global can work, but it should only be used if you can't pass the variable through the function as it has some security risk...

$GLOBALS["settings"]["template"]["value"] = 'yes';

This works because it changes the scope of the variable to be global.

$GLOBALS["settings"]["template"]["value"] = 'yes';

function test(){

    echo $GLOBALS["settings"]["template"]["value"];

}

test();

The above prints out yes

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top