PhP Variables inside functions - php

I'm having troubles with variables inside functions and being able to read them in a index.php. Let's say I have this function (functions.php):
function firstFunction(){
$id = '1234';
secondFunction($id);
}
function secondFunction($idnumber){
if( $idnumber = 1234 ){
$name = "James"; //should say "james".
}
and in the index.php have something like that:
include(functions.php)
<?php
firstFunction();
echo $name;
?>
does anyone know a possible way to do this?, i need to be a able to read from a variable inside a function that is in another function.
Also when calling a function inside a function allow this to read a variable from the first function.
Thanks.

Variables created inside a function are local to it, you can't read their contents outside of it (because all function-local variables get deleted after the function finished running).
The improper way would be to make the $name variable global in the second function.
A better way to do it would be to use function return values: secondFunction returns $name, and firstFunction returns whatever it gets from calling secondFunction($id).
Oh, and by the way, you have another logical error in your secondFunction: Your if test will not behave like you probably intended because you are using a variable value assignment operator (=) instead of comparison (==) which always succeeds returns the assigned value that evaluates to a "true" value in most (but not all) cases.

This is very bad practice - using globals. The answer you need is:
global $name;
You need to put it above the row:
$name = "James"; //should say "james".

You declare $name inside second function, so it only exists there (that is it's "Scope").
To use it's value you need the functions to return it:
function secondFunction($idnumber){
if ( $idnumber == 1234 ){
$name = "James"; //should say "james".
}
else {
$name = "";
}
return $name;
}
function firstFunction(){
$id = 1234;
return secondFunction($id);
}
and in the index.php have something like that:
<?php
include 'functions.php';
$name = firstFunction();
echo $name;
?>

You can't call a variable like that it is out of scope what you need to do is as follows
function firstFunction(){
$id = '1234';
return secondFunction($id);
}
function secondFunction($idnumber){
if( $idnumber == 1234 ){
return "James";
}
}
Then in your index do this
<?php
include(functions.php);
echo firstFunction();
?>
A variable that is out of scope can not be accessed for example if you defined a variable inside a if statement is would only be able to be used in that statement and it is the same with the functions and variables that are inside. Thought I needed to explain my answer more.

Try this...
index.php
<?php
// Includes
include("functions.php");
// Create a variable to store the output of your function
$returned_name = firstFunction();
// Echo the variable
echo "Name: " . $returned_name;
?>
functions.php
<?php
// Function 1
function firstFunction() {
$id = "1234";
return secondFunction($id);
}
// Function 2
function secondFunction($idnumber) {
if ($idnumber == "1234") {
$name = "James";
} else if ($idnumber == "5678") {
$name = "Brian";
}
return $name;
}
?>

Related

Access a global variable in a PHP function

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;
}

how can i make a function see a variable outside it

How can I place a variable inside a function when it is run in order to preg_match the right information. Here is my existing code:
$username = "test";
function is_txt($file) {
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9]{2}_'.$username.'.tar.gz/', $file) > 0;
}
What I am attempting to do is pull the $username variable from outside the function and allow it to be seen within it so I can pull the right matches in my while loop. While the previous comes back blank, if i do the following it works:
$username = "test";
function is_txt($file) {
$username = "test";
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9]{2}_'.$username.'.tar.gz/', $file) > 0;
}
Modify the function to take the $username variable as a parameter:
function is_txt($file, $u) {
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9]{2}_'.$u.'.tar.gz/', $file) > 0;
}
Then call it like:
$username = "test";
is_txt($file, $username);
Alternatively, you can use the global keyword to make the variable visible from the function. This is sometimes useful, but shouldn't be used all over the place. See the variable scope manual entry for more info.
You need to import the var with global:
function is_txt($file) {
global $username;
return preg_match('/backup-[0-9]+\.[0-9]+\.[0-9]+_[0-9]{2}-[0-9]{2}-[0-9] {2}_'.$username.'.tar.gz/', $file) > 0;
}
But passing the value in as a parameter as explained by Jonah is a better solution in most cases.

Call Function Based On Parameter Name

I am passing a parameter, "action", to another file, process.php. The value of "action" will be the name of a function that is defined within process.php. If the function exists, it should be called automatically. I tried the following:
$action = $_REQUEST['action'];
$function = {$action}();
if(function_exists($function))
$function;
else
die('No function.');
That, however, does not work. Any suggestions? Thanks!
As #Positive said you are calling the function on assignment. I just wanted to add a few things - this is a bit risky - what if the request contents were 'phpinfo' or something even more dangerous. Perhaps a better idea would be to select the function from an array of allowed functions:
$allowed_functions = array(
'my_function_one',
'my_function_two'
);
$action = $_REQUEST['action'];
if(in_array($action,$allowed_functions)){
{$action}();
}
else {
die('No function.');
}
Change the assignment to $function like below. Note that function_exists only take the function name.
$action = $_REQUEST['action'];
$function = $action;
Actually you are calling the function with this statment $result = $function();, see Variable functionsPHP-Manual.
and also sanitize the GET parameter according to your function name conventions.

How to get a strings data from a different function?

I have a php file with different functions in it. I need to get data from strings in a function, but the strings have been specified in a different function. How can this be done please?
... To clarify, I have two functions.
function a($request) { $username = ...code to get username; }
the username is over retreivable during function a.
function b($request) { }
function b need the username, but cannot retrieve it at the point its called, so need it from function a. I am very much a beginer here (so bear with me please), I tried simply using $username in function b, but that didn't work.
Can you please explain how I can do this more clearly please. There are another 5 strings like this, that function b needs from function a so I will need to do this for all the strings.
...Code:
<?php
class function_passing_variables {
function Settings() {
//function shown just for reference...
$settings = array();
$settings['users_data'] = array( "User Details", "description" );
return $settings;
}
function a( $request ) {
//This is the function that dynamically gets the user's details.
$pparams = array();
if ( !empty( $this->settings['users_details'] ) ) {
$usersdetails = explode( "\n", Tool::RW( $this->settings['users_data'], $request ) );
foreach ( $usersdetails as $chunk ) {
$k = explode( '=', $chunk, 2 );
$kk = trim( $k[0] );
$pparams[$kk] = trim( $k[1] );
}
}
$email=$pparams['data_email'];
$name=$pparams['data_name'];
$username=$pparams['data_username'];
//These variables will retrieve the details
}
function b( $request ) {
//Here is where I need the data from the variables
//$email=$pparams['data_email'];
//$name=$pparams['data_name'];
//$username=$pparams['data_username'];
}
}
?>
#A Smith, let me try to clarify what you mean.
You have several variables, example : $var1, $var2, etc.
You have two function (or more) and need to access that variables.
If that what you mean, so this may will help you :
global $var1,$var2;
function a($params){
global $var1;
$var1 = 1;
}
function b($params){
global $var1,$var2;
if($var1 == 1){
$var2 = 2;
}
}
Just remember to define global whenever you want to access global scope variable accross function. You may READ THIS to make it clear.
EDITED
Now, its clear. Then you can do this :
class function_passing_variables{
// add these lines
var $email = "";
var $name = "";
var $username = "";
// ....
Then in your function a($request) change this :
$email=$pparams['data_email'];
$name=$pparams['data_name'];
$username=$pparams['data_username'];
to :
$this->email=$pparams['data_email'];
$this->name=$pparams['data_name'];
$this->username=$pparams['data_username'];
Now, you can access it in your function b($request) by this :
echo $this->email;
echo $this->name;
echo $this->username;
In the functions where the string has been set:
Global $variable;
$variable = 'string data';
Although you really should be returning the string data to a variable, then passing said variable to the other function.

PHP newbie question: return variable with function?

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

Categories