views:

156

answers:

3

I'm writing a bit of the code and I have parent php script that does include() and includes second script, here is snippet from my second code:

echo ($GLOBALS['key($_REQUEST)']);

I'm trying to grab a key($_REQUEST) from the parent and use it in child, but that doesn't work..

this is when I run script using command line:

mbp:digaweb alexus$ php findItemsByKeywords.php test
PHP Notice:  Undefined index: key($_REQUEST) in /Users/alexus/workspace/digaweb/findItemsByKeywords.php on line 3
PHP Stack trace:
PHP   1. {main}() /Users/alexus/workspace/digaweb/findItemsByKeywords.php:0
mbp:digaweb alexus$ 

i heard that globals isn't recommended way also, but i don't know maybe it's ok...

A: 
echo $_GLOBALS[key($_REQUEST)];

You just need to remove the single quotation marks. It was looking for the literal 'key($_REQUEST)' key, which obviously doesn't exist.

It all depends on what you are trying to do though... what are you trying to do?

James Skidmore
when I tried your example, I'm getting: PHP Notice: Undefined variable: _GLOBALS, what I'm trying to do is to pass that key($_REQUEST) to my child script that I called through include(), I need to pass something to that script form parent script
alexus
A: 

Based on your comment to my other answer, I think I understand what you're trying to do. You're just trying to pass a variable from one script into another script that's included.

As long as you define a variable before you include the script, it can be used in the included script. For instance:

// script1.php
$foo = 'bar';
include_once('script2.php');

// script2.php
echo $foo; // prints "bar"
James Skidmore
i'll give it a shot, but for now and I dont know if this is best practice, i did through making my script2 as a function.
alexus
+2  A: 

$_REQUEST is a superglobal and will be directly available inside of any function or script, so you don't need to worry about passing it to the child script. However, PHP won't populate $_REQUEST when used from the command line, unless you're using a configuration option I'm unfamiliar with. You'll need to use the $_SERVER['argv'] array.

Globals are indeed not recommended. You'll have an easier time long-term if you go with what outis suggested. Here's an example:

script1.php:
<?php
$file = $_SERVER['argv'][1]; // 0 is the script's name

require_once ('script2.php');

$result = doSomething ($file);
echo $result;
?>

script2.php:
<?php
function doSomething ($inputfile)
{
  $buf = file_get_contents($inputfile);
  $buf = strtolower($buf); // counts as something!
  return $buf;
}
?>

This example doesn't make use of the key($_REQUEST), but I'm not sure what the purpose of that is so I just went with $_SERVER['argv'].

dpk