Can anyone tell me why this works (it echos out "poo"):
$input = "wee";
$val = "poo";
${$input} = $val;
echo $wee;
But this doesn't:
function bodily($input) {
$val = "poo";
${$input} = $val;
}
bodily("wee");
echo $wee;
I want to use this sort of method to play with some $_POST vars. Please tell me if I can explain more... Cheers!
Your variable $wee gets only defined inside the scope of your function bodily(). It is not defined outside this function.
You could make it global, anyway this is not a useful pattern for a real life application:
function bodily($input) {
$val = "poo";
global ${$input}; // make your $wee defined in the global scope
${$input} = $val;
}
bodily("wee");
echo $wee;
outputs
poo
Because the variable is defined locally inside of the function. Let the function return the value and assign it to a variable outside of the function.
Because the variables inside a function are not accessible from outside unless inside the function you use "global $var" or pass it by reference like function (&$var) ...
in order for your code to work you need
<?php
function bodily($input) {
$val = "poo";
${$input} = $val;
echo $wee;
}
bodily("wee");
Related
How would I alter the function below to produce a new variable for use outside of the function?
PHP Function
function sizeShown ($size)
{
// *** Continental Adult Sizes ***
if (strpos($size, 'continental-')!== false)
{
$size = preg_replace("/\D+/", '', $size);
$searchsize = 'quantity_c_size_' . $size;
}
return $searchsize;
Example
<?php
sizeShown($size);
$searchsize;
?>
This currently produces a null value and Notice: undefined variable.
So the function takes one argument, a variable containing a string relating to size. It checks the variable for the string 'continental-', if found it trims the string of everything except the numbers. A new variable $searchsize is created which appends 'quantity_c_size_' to the value stored in $size.
So the result would be like so ... quantity_c_size_45
I want to be able to call $searchsize outside of the function within the same script.
Can anybody provide a solution?
Thanks.
Try using the global keyword, like so:
function test () {
global $test_var;
$test_var = 'Hello World!';
}
test();
echo $test_var;
However, this is usually not a good coding practice. So I would suggest the following:
function test () {
return 'Hello World!';
}
$test_var = test();
echo $test_var;
In the function 'sizeShown' you are just returning the function. You forgot to echo the function when you call your function.
echo sizeShown($size);
echo $searchsize;
?>
But the way you call $searchsize is not possible.
This is an old question, and I might not be understanding the OP's question properly, but why couldn't you just do this:
<?php
$searchsize = sizeShown($size);
?>
You're already returning $searchsize from the sizeShown method. So if you simply assign the result of the function to the $sizeShown variable, you should have what you want.
According to the most programming languages scope rules, I can access variables that are defined outside of functions inside them, but why doesn't this code work?
<?php
$data = 'My data';
function menugen() {
echo "[" . $data . "]";
}
menugen();
?>
The output is [].
To address the question as asked, it is not working because you need to declare which global variables you'll be accessing in the function itself:
$data = 'My data';
function menugen() {
global $data; // <-- Add this line
echo "[" . $data . "]";
}
menugen();
Otherwise you can access it as $GLOBALS['data'], see Variable scope.
Even if a little off-topic, I would suggest you avoid using globals at all and prefer passing data as parameters.
In this case, the above code look like this:
$data = 'My data';
function menugen($data) { // <-- Declare the parameter
echo "[" . $data . "]";
}
menugen($data); // <-- And pass it at call time
You can do one of the following:
<?php
$data = 'My data';
function menugen() {
global $data;
echo "[" . $data . "]";
}
menugen();
Or
<?php
$data = 'My data';
function menugen() {
echo "[" . $GLOBALS['data'] . "]";
}
menugen();
That being said, overuse of globals can lead to some poor code. It is usually better to pass in what you need. For example, instead of referencing a global database object you should pass in a handle to the database and act upon that. This is called dependency injection. It makes your life a lot easier when you implement automated testing (which you should).
Another way to do it:
<?php
$data = 'My data';
$menugen = function() use ($data) {
echo "[".$data."]";
};
$menugen();
UPDATE 2020-01-13: requested by Peter Mortensen
As of PHP 5.3.0 we have anonymous functions support that can create closures. A closure can access the variable which is created outside of its scope.
In the example, the closure is able to access $data because it was declared in the use clause.
It's a matter of scope. In short, global variables should be avoided so:
You either need to pass it as a parameter:
$data = 'My data';
function menugen($data)
{
echo $data;
}
Or have it in a class and access it
class MyClass
{
private $data = "";
function menugen()
{
echo this->data;
}
}
See #MatteoTassinari answer as well, as you can mark it as global to access it, but global variables are generally not required, so it would be wise to re-think your coding.
For many years I have always used this format:
<?php
$data = "Hello";
function sayHello(){
echo $GLOBALS["data"];
}
sayHello();
?>
I find it straightforward and easy to follow. The $GLOBALS is how PHP lets you reference a global variable. If you have used things like $_SERVER, $_POST, etc. then you have reference a global variable without knowing it.
I was looking for this answer, sort of, I wanted to see if anyone else had something similar with respect to how $prefix would be passed to an anonymous function. Seems the global scope is the the way? This is my solution for prefixing an array in a non-destructive manner.
private function array_prefix($prefix, $arr) {
$GLOBALS['prefix'] = $prefix;
return array_map(
function($ele) {
return $GLOBALS['prefix'].$ele;
},
$arr
);
}
<?php
$data = 'My data';
$menugen = function() use ($data) {
echo "[ $data ]";
};
$menugen();
?>
You can also simplify
echo "[" . $data . "]"
to
echo "[$data]"
PHP can be frustrating for this reason. The answers above using global did not work for me, and it took me awhile to figure out the proper use of use.
This is correct:
$functionName = function($stuff) use ($globalVar) {
//do stuff
}
$output = $functionName($stuff);
$otherOutput = $functionName($otherStuff);
This is incorrect:
function functionName($stuff) use ($globalVar) {
//do stuff
}
$output = functionName($stuff);
$otherOutput = functionName($otherStuff);
Using your specific example:
$data = 'My data';
$menugen = function() use ($data) {
echo "[" . $data . "]";
}
$menugen();
The proper way for accessing a global variable inside a function is answered above!
BUT if you do not want to use the global keyword, nor the $GLOBALS variable for some reason (for example you have multiple functions and you are "tired" of writing global $variable; every time), here is a workaround:
$variable = 42; // the global variable you want to access
// write a function which returns it
function getvar(){
global $variable;
return $variable;
}
//--------------
function func1()
{
// use that getter function to get the global variable
echo getvar(); // 42
}
function func2()
{
echo getvar(); // 42
}
...
You need to pass the variable into the function:
$data = 'My data';
function menugen($data)
{
echo $data;
}
I am having trouble returning a value from a multidimensional array using a key ONLY when I externalize to create a function.
To be specific, the following code will work when inline in a page:
<?php
foreach ($uiStringArray as $key) {
$keyVal = $key['uid'];
if($keyVal == 'global001') echo $key['uiString'];
}
?>
However, if I externalize the code as a function, like so:
function getUIString($myKey) {
// step through the string array and find the key that matches the uid,
// then return uiString
$myString = "-1";
foreach ($uiStringArray as $key) {
$keyVal = $key['uid'];
if($keyVal == 'global001') {
$myString = $key['uiString'];
}
}
return $myString;
}
And then call it like this:
<?php getUIString('global001'); ?>
It always returns -1, and will do so even if I use an explicit key in the function rather than a variable. I can't understand why this works inline, but fails as a function.
I'm a relative PHP noob, so please forgive me if this includes a glaring error on my part, but I've searched all over for discussion of this behavior and found none.
All help appreciated.
i think you need to take a look at PHP's Variable Scope. To problem is that PHP isn't typical of other languages where a variable defined outside of a function is visible within. You need to use something like the $GLOBALS variable or declare the variable global to access it.
To better illustrate, picture the following:
$foo = "bar";
function a(){
// $foo is not visible
echo $foo;
}
function b(){
global $foo; // make $foo visible
echo $foo;
}
function c(){
// acccess foo within the global space
echo $GLOBALS['foo'];
}
The same is basically holding true for your $uiStringArray variable in this scenario.
This is a problem with variable scope, see Brad Christie's answer for more details on variable scope.
As for your example, you need to either pass the array to the function or create it inside the function. Try:
function getUIString($myKey, $uiStringArray = array()) {
// step through the string array and find the key that matches the uid,
// then return uiString
$myString = "-1";
foreach ($uiStringArray as $key) {
$keyVal = $key['uid'];
if($keyVal == 'global001') {
$myString = $key['uiString'];
break;
}
}
return $myString;
}
And call the function using
<?php getUIString('global001', $uiStringArray); ?>
You are having this problem because you are overriding you $mystring variable even if it matches. Send your array as your parameter. It is unknown to your function.You just use break if variable matches
function getUIString($myKey, $uiStringArray=array()) {
// step through the string array and find the key that matches the uid,
// then return uiString
$myString = "-1";
foreach ($uiStringArray as $key) {
$keyVal = $key['uid'];
if($keyVal == 'global001') {
$myString = $key['uiString'];
break;
}
}
return $myString;
}
i've been coding asp and was wondering if this is possible in php:
$data = getData($isEOF);
function getData($isEOF=false)
{
// fetching data
$isEOF = true;
return $data;
}
the function getData will return some data, but i'd like to know - is it possible to also set the $isEOF variable inside the function so that it can be accessed from outside the function?
thanks
It is possible, if your function expects it to be passed by reference :
function getData(& $isEOF=false) {
}
Note the & before the variable's name, in the parameters list of the function.
For more informations, here's the relevant section of the PHP manual : Making arguments be passed by reference
And, for a quick demonstration, consider the following portion of code :
$value = 'hello';
echo "Initial value : $value<br />";
test($value);
echo "New value : $value<br />";
function test(& $param) {
$param = 'plop';
}
Which will display the following result :
Initial value : hello
New value : plop
Using the global statement you can use variables in any scope.
$data = getData();
function getData()
{
global $isEOF;
// fetching data
$isEOF = true;
return $data;
}
See http://php.net/manual/en/language.variables.scope.php for more info.
Yes, you need to pass the variable by reference.
See the example here : http://www.phpbuilder.com/manual/functions.arguments.php
In my includes folder I have a function...
function storelistingUno() {
$itemnum=mysql_real_escape_string($_POST['itemnum']);
$msrp=mysql_real_escape_string($_POST['msrp']);
$edprice=mysql_real_escape_string($_POST['edprice']); //This value has to be the same as in the HTML form file
$itemtype=mysql_real_escape_string($_POST['itemtype']);
$box=mysql_real_escape_string($_POST['box']);
$box2=mysql_real_escape_string($_POST['box2']);
$box25=mysql_real_escape_string($_POST['box25']);
$box3=mysql_real_escape_string($_POST['box3']);
$box4=mysql_real_escape_string($_POST['box4']);
$box5=mysql_real_escape_string($_POST['box5']);
$box6=mysql_real_escape_string($_POST['box6']);
$box7=mysql_real_escape_string($_POST['box7']);
$box8=mysql_real_escape_string($_POST['box8']);
$itemcolor=mysql_real_escape_string($_POST['itemcolor']);
$link=mysql_real_escape_string($_POST['link']);
$test = "yes!";
}
I reference this in about 8 pages and I decided it would be easier to just make a function out of it and only touch this from now on. So I referenced storelistingUno(); in my code, but I don't think it worked, because I tried to execute echo $test; and nothing happened. Do I need to return something?
Thanks.
Look into extract(). You can do something like this:
<?php
function getEscapedArray()
{
$keys = array('itemnum', 'msrp', 'edprice', 'itemtype', 'box', 'box2', 'box25', 'box3', 'box4', 'box5', 'box6', 'box7', 'box8', 'itemcolor', 'link');
$returnValues = array();
foreach ($keys as $key) {
$returnValues[$key] = mysql_real_escape_string($_POST[$key]);
}
$returnValues['test'] = 'yes!';
return $returnValues;
}
extract(getEscapedArray());
echo $test;
Although - Its still not the best way to do this. The best would be to just use the return from that function as the array.
$parsedVals = getEscapedArray();
echo $parsedVals["test"];
If you absolutely need these variables a globals
function storelistingUno()
{
$desiredGlobals = array(
'itemnum'
,'msrp'
,'edprice'
,'itemtype'
,'box'
,'box2'
,'box25'
,'box3'
,'box4'
,'box5'
,'box6'
,'box7'
,'box8'
,'itemcolor'
,'link'
);
foreach ( $desiredGlobals as $globalName )
{
if ( isset( $_POST[$globalName] ) )
{
$GLOBALS[$globalName] = mysql_real_escape_string( $_POST[$globalName] );
}
}
}
$test is a local variable in that function - you either need to make it global (by putting global $test; at the start of the function or using $GLOBALS['test'] instead of just $test or return the value.
Are you thinking of using that function to just escape the values? Maybe you could make it perform the query too, then you wouldn't have to return / use globals.
Edit:
A different way would be to include the code instead of using a function - not recommended though...
You would have to mark every variable as global before you start to edit them within the function ... this isn't recommented since it's bad coding style but it might help you
$test = '';
function foo() {
global $test;
$test = 'bar';
}
echo $test; //prints nothing
foo();
echo $test; // prints "bar"