PHP function use variable from outside
Add second parameter
You need to pass additional parameter to your function:
function parts($site_url, $part) {
$structure = 'http://' . $site_url . 'content/';
echo $structure . $part . '.php';
}
In case of closures
If you'd rather use closures then you can import variable to the current scope (the use
keyword):
$parts = function($part) use ($site_url) {
$structure = 'http://' . $site_url . 'content/';
echo $structure . $part . '.php';
};
global
- a bad practice
This post is frequently read, so something needs to be clarified about global
. Using it is considered a bad practice (refer to this and this).
For the completeness sake here is the solution using global
:
function parts($part) {
global $site_url;
$structure = 'http://' . $site_url . 'content/';
echo($structure . $part . '.php');
}
It works because you have to tell interpreter that you want to use a global variable, now it thinks it's a local variable (within your function).
Suggested reading:
- Variable scope in PHP
- Anonymous functions
Access variable from outside function (PHP)
Insert this inside the function:
global $ERROR;
So, the variable can be accessed inside the function scope (see global keyword).
function validateLogin($data) {
global $ERROR;
...
}
Alternatively you can access to all variables that are outside the function using $GLOBALS:
$GLOBALS['ERROR']
How to assign a variable outside php function
You can request a reference in the function body.
function assign_check(&$variable, $check) {
$variable = 'hello';
}
And call passing a variable (reference).
assign_check($admin, 'admin');
$admin
value is now 'hello';
Fitting that to your code would result in
function assign_check(&$variable, $check) {
$variable = empty($_POST[$check]) ? "no" : $_POST[$check];
}
assign_check($admin', 'admin');
But returning a proper value would be much cleaner code than using references. Using a ternary operator like presented above would it even simplify without need of a function at all.
Giving my function access to outside variable
By default, when you are inside a function, you do not have access to the outer variables.
If you want your function to have access to an outer variable, you have to declare it as global
, inside the function :
function someFuntion(){
global $myArr;
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
}
For more informations, see Variable scope.
But note that using global variables is not a good practice : with this, your function is not independant anymore.
A better idea would be to make your function return the result :
function someFuntion(){
$myArr = array(); // At first, you have an empty array
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal; // Put that $myVal into the array
return $myArr;
}
And call the function like this :
$result = someFunction();
Your function could also take parameters, and even work on a parameter passed by reference :
function someFuntion(array & $myArr){
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal; // Put that $myVal into the array
}
Then, call the function like this :
$myArr = array( ... );
someFunction($myArr); // The function will receive $myArr, and modify it
With this :
- Your function received the external array as a parameter
- And can modify it, as it's passed by reference.
- And it's better practice than using a global variable : your function is a unit, independant of any external code.
For more informations about that, you should read the Functions section of the PHP manual, and,, especially, the following sub-sections :
- Functions arguments
- Returning values
Php get function variable outside not working
since the variables '$var','$var2' and '$var3' are local variable for the function variables so it has no existence unless the function is called or executed.
So there are two methods to fix your issue
Method one make the variable global.
<?php
// Declaring the global veriable
$var=0;
$var2=0;
$var3=0;
function variables()
{ // method 2 to declare global
GLOBAL $var = rand(1111,9999);
GLOBAL $var2 = rand(11111,99999);
GLOBAL $var3 = rand(111111,999999);
}
but still, if u want to get the rand
value from the function u need to call the function at least once
// calling the function
variables();
echo variables([$var]);
echo variables([$var2]);
echo variables([$var3]);
?>
hope you got the solution if not just comment I will help u out with this for sure
Get variables from the outside, inside a function in PHP
You'll need to use the global keyword inside your function.
http://php.net/manual/en/language.variables.scope.php
EDIT (embarrassed I overlooked this, thanks to the commenters)
...and store the result somewhere
$var = '1';
function() {
global $var;
$var += 1; //are you sure you want to both change the value of $var
return $var; //and return the value?
}
PHP pass variable outside of function without global variables
John Conde is right but to show you the code it would be
<?php
function hello() {
$x = 2;
return $x;
}
$var = hello();
echo $var;
?>
PHP using variables outside of a function
function adminCharge(&$subTotal){
// do things
}
or
$subTotal = adminCharge($subTotal);
function adminCharge($subTotal){
//do things
return $subTotal;
}
In the first case, you pass $subTotal
variable as a reference, so all all changes will be reflected to "outside" variable.
In the second case, you pass it and return new value, so is easy to understand why is working.
Please, pay attention
First solution - however - can lead you to side effect that will be difficult to understand and debug
Update
If you want to "extract" (so return) two variables, you can do the following
list($subTotal,$packagingPrice) = adminCharge($subTotal);
function adminCharge($subTotal){
if(isset($packagingPrice)){
$subTotal = $subTotal + $packagingPrice;
}
return array($subTotal, $packagingPrice);
}
Why is external variable out of scope to PHP function?
in php if you want to use any variable inside any function without passing it in parameter. you need to defined it as global. it before using you need global $dbConnect
.
<?php
//constants for database connection
define(DB_RESOURCE, "192.168.99.67");
define(DB_USERNAME, "myUsername");
define(DB_PASSWORD, "p@ssword");
define(DB_NAME, "myDatabase");
//variable defined here so why can't function see it?
$dbConnect = mysqli_connect(DB_RESOURCE, DB_USERNAME, DB_PASSWORD, DB_NAME);
function readData($table, $column) {
$sql = "SELECT {$column} FROM {table}";
//redefining this solves the problem but why is this needed?
global $dbConnect;
// now you can use $dbConnect. In php you need to specify it as global once inside the block after it you can use
$data = mysqli_query($dbConnect, $sql);
}
?>
Related Topics
List and Download Clicked File from Ftp
Simple PHP SQL Login Troubleshooting
PHP Regex Delimiter, What's the Point
PHP Alternative to Session_Is_Registered
How Follow the Don't Repeat Yourself Principle When Consuming My Own Laravel API
Get Woocommerce Product Categories from Wordpress
Adding Subscribers to a List Using Mailchimp's API V3
Do Ajax Requests Retain PHP Session Info
Check If a Row Exists Using Old MySQL_* API
For Loop VS While Loop VS Foreach Loop PHP
Get All MySQL Selected Rows into an Array
Handling Big User Ids Returned by Fql in PHP
Get MySQL Query Results as Their Native Data Type
What Is Better in a Foreach Loop... Using the & Symbol or Reassigning Based on Key
Xdebug V3 Doesn't Stop Breakpoints in VScode
Simplexml How to Prepend a Child in a Node
Codeigniter Default Controller in a Sub Directory Not Working