This question already has answers here:
Can't access global variable inside function
(5 answers)
Closed 9 years ago.
i need to access a variable which is declared in another php file within a function.. How can i do it?
a.php
<?php
$global['words']=array("one","two","three");
echo "welcome"
?>
b.php
<?php
$words = $global['words'];
require_once('a.php');
print_r($global['words']);
function fun()
{
print_r($global['words']); // not displaying here
}
fun();
?>
now i am able to access the "$global['words']" variable in b.php file, but not within function, how can i make it visible inside the function?
The preferred option is to pass as a parameter:
function fun($local) {
print_r($local['words']);
}
fun($global);
If for some reason you can't use that approach, then you can declare the variable as global:
function fun() {
global $global;
print_r($global['words']);
}
fun();
Or use the $GLOBALS array:
function fun() {
print_r($GLOBALS['global']['words']);
}
fun();
But in general, using global variables is considered bad practise.
actually your function does n't know about anything outside it, if it's not a classes, or global php vars such as $_POST , you can try to define function as:
function fun() use ($globals)
{
}
Related
This question already has answers here:
Are PHP Variables passed by value or by reference?
(16 answers)
How to declare a global variable in php?
(10 answers)
Closed 3 years ago.
I would like to be able to assign the name of a variable outside the function so that the function can assign the chosen variable. It does not seem to work. Anyone have any ideas?
Below is my attempt, however the $admin variable is empty after running the function.
function assign_check($variable, $check) {
if (empty($_POST[$check])) {
$variable = "no";
} else {
$variable = $_POST[$check];
}
}
assign_check('$admin', 'admin');
My question is not about the use of global variables.
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.
A normal way to assign the result of a function to a variable name specified outside the function would be to have the function return the result and assign it directly to the variable when you call the function.
function assign_check($check) {
if (empty($_POST[$check])) {
return "no";
} else {
return $_POST[$check];
}
}
$admin = assign_check('admin');
I would do it this way unless there was a compelling reason to do it otherwise.
For the specific type of thing it looks like this function is intended to do, I would suggest looking at filter_input.
This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 5 years ago.
This is really simple but I can't get my head around it. I am setting a datestamp and would like to be able to use it inside a function like this..
$date_stamp = date("dmy",time());
function myfunction() {
echo $date_stamp;
}
This is not working and $date_stamp is not available inside the function, how can I use this?
This is basic PHP. $date_stamp is out of scope within your function. To be in scope you must pass it as a parameter:
$date_stamp = date("dmy",time());
function myfunction($date) {
echo $date;
}
// call function
myfunction($date_stamp);
See PHP variable scope.
Just as an add-on to John Conde's answer, you can also use a closure like so
<?php
$date_stamp = date("dmy",time());
$myfunction = function() use ($date_stamp) {
echo '$myfunction: date is '. $date_stamp;
};
$myfunction();
I would like to use a values stored in a seperate file in a static function in a PHP class.
Example:
<?php
include "vars.php";
class MyClass {
public static function doSomething() {
echo "Default value is ".$default_value;
}
}
MyClass::doSomething();
?>
And in vars.php
<?php
$default_value = "DEFAULT";
?>
I get following error:
Notice: Undefined variable: default_value in C:\xampp\htdocs\mediamanager\new_hp\MyClass.php on line 6
Default value is
How would this be possible? Or is there a better way to read configuration values from a seperate file?
You could declare $default as a global variable using the global keyword, or put it into the GLOBALS superglobal.
Ps: For configuration, I would personally use a class, with constant members.
This question already has answers here:
How to call a function from a string stored in a variable?
(18 answers)
Closed 1 year ago.
I found question from here. But I need to call function name with argument.
I need to be able to call a function, but the function name is stored in a variable, is this possible? e.g:
function foo ($argument)
{
//code here
}
function bar ($argument)
{
//code here
}
$functionName = "foo";
$functionName($argument);//Call here foo function with argument
// i need to call the function based on what is $functionName
Anyhelp would be appreciate.
Wow one doesn't expect such a question from a user with 4 golds. Your code already works
<?php
function foo ($argument)
{
echo $argument;
}
function bar ($argument)
{
//code here
}
$functionName = "foo";
$argument="Joke";
$functionName($argument); // works already, might as well have tried :)
?>
Output
Joke
Fiddle
Now on to a bit of theory, such functions are called Variable Functions
PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.
If you want to call a function dynamically with argument then you can try like this :
function foo ($argument)
{
//code here
}
call_user_func('foo', "argument"); // php library funtion
Hope it helps you.
you can use the php function call_user_func.
function foo($argument)
{
echo $argument;
}
$functionName = "foo";
$argument = "bar";
call_user_func($functionName, $argument);
if you are in a class, you can use call_user_func_array:
//pass as first parameter an array with the object, in this case the class itself ($this) and the function name
call_user_func_array(array($this, $functionName), array($argument1, $argument2));
I hava a function that looks something like this:
require("config.php");
function displayGta()
{
(... lots of code...)
$car = $car_park[3];
}
and a config.php that look something like this:
<?php
$car_park = array ("Mercedes 540 K.", "Chevrolet Coupe.", "Chrysler Imperial.", "Ford Model T.", "Hudson Super.", "Packard Sedan.", "Pontiac Landau.", "Duryea.");
(...)
?>
Why do I get Notice: Undefined variable: car_park ?
Try adding
global $car_park;
in your function. When you include the definition of $car_park, it is creating a global variable, and to access that from within a function, you must declare it as global, or access it through the $GLOBALS superglobal.
See the manual page on variable scope for more information.
Even though Paul describes what's going on I'll try to explain again.
When you create a variable it belongs to a particular scope. A scope is an area where a variable can be used.
For instance if I was to do this
$some_var = 1;
function some_fun()
{
echo $some_var;
}
the variable is not allowed within the function because it was not created inside the function. For it to work inside a function you must use the global keyword so the below example would work
$some_var = 1;
function some_fun()
{
global $some_var; //Call the variable into the function scope!
echo $some_var;
}
This is vice versa so you can't do the following
function init()
{
$some_var = true;
}
init();
if($some_var) // this is not defined.
{
}
There are a few ways around this but the simplest one of all is using $GLOBALS array which is allowed anywhere within the script as they're special variables.
So
$GLOBALS['config'] = array(
'Some Car' => 22
);
function do_something()
{
echo $GLOBALS['config']['some Car']; //works
}
Also make sure your server has Register globals turned off in your INI for security.
http://www.php.net/manual/en/security.globals.php
You could try to proxy it into your function, like:
function foo($bar){
(code)
$car = $bar[3];
(code)
}
Then when you call it:
echo foo($bar);
I had the same issue and have been tearing my hair out over it - nothing worked, absolutely nothing - until in desperation I just copied the contents of config.php into a new file and saved it as config2.php (without changing anything in its contents at all), changed the require_once('config.php'); to require_once('config2.php'); and it just started working.