开发者

Passing Variable FROM Included PHP File To Parent Script

I include a PHP file to the HEADER of my WordPress site, which searches through a CSV file and returns me the variable I need. I am trying to have it included in the header because it's a variable I will need throughout the site later on. If I test it out and try to echo this variable from the included script, it works fine. However, in the rest of the site, if I try to call that variable it doesn't return anything.

I know that the variable is being created because I try to echo it and it works. But when the I try to use that variable from a different script, it doesn't work. Is there some kind of code I need to pass the variable o开发者_开发技巧ver to the rest of the site?


Variables default to function level only, you have to pass them or globalize them if you want to use them elsewhere. Depending on how your script is laid out, you might make it an object property, in which case it will be available anywhere your object is available and in all methods of that object - another option is to use global $var, but that's a bad idea and bad coding practice - another is to put it into a session using $_SESSION['myVar'] = $var and then call it the same way - yet another way is to pass it through arguments such as $database->getRows($var) and then on the other side "public function getRows ($var)", now you have $var in that function by passing it.


Make sure you global $variable the variable everytime you want to use it in a new function, or even within a new script. This will make sure that the variable is available everywhere that you need it.


3 files:

a.php:

<?php
include("c.php");

var_dump("c is ".$c . " after include()");

function incit(){
    include("b.php");
    var_dump("b is ".$b . " inside incit()");
}

incit();
var_dump("b is ".$b . " after incit()");



?>

b.php:

<?php
$b="bear";
?>

c.php:

<?php
$c="car";
?>

output looks like this:

string(24) "c is car after include()" 
string(24) "b is bear inside incit()" 
string(19) "b is after incit()" 

so $b is only defined INSIDE the scope of the function while $c on the other hand is "globally" definde. So you have to watch in what scope you are using the include.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜