Im trying to change the value of a declared variable which is outside the function in use of a function
<?php
$test = 1;
function addtest() {
$test = $test + 1;
}
addtest();
echo $test;
?>
but it seems it couldn't. only variables declared as parameters in the function only work. is there a technique for this? thanks in advance
Change the variable inside the function to a global -
function addtest() {
global $test;
$test = $test + 1;
}
There are a lot of caveats to using global variables -
your code will be harder to maintain over the long run because globals may have an undesired affect on future calculations where you might not be aware how the variable was manipulated.
if you refactor the code and the function goes away it will be detrimental because every instance of $test is tightly coupled to the code.
Here is a slight improvement and doesn't require global -
$test = 1;
function addtest($variable) {
$newValue = $variable + 1;
return $newValue;
}
echo $test; // 1
$foo = addtest($test);
echo $foo; // 2
Now you haven't had to use a global and you have manipulated $test to your liking while assigning the new value to another variable.
Not sure if this is a contrived example or not, but in this case (as in most cases) it would be extremely bad form to use global. Why not just return the results and assign the return value?
$test = 1;
function increment($val) {
return $val + 1;
}
$test = increment($test);
echo $test;
This way, if you ever need to increment any other variable besides $test, you're done already.
If you need to change multiple values and have them returned, you can return an array and use PHP's list to easily extract the contents:
function incrementMany($val1, $val2) {
return array( $val1 + 1, $val2 + 1);
}
$test1 = 1;
$test2 = 2;
list($test1, $test2) = incrementMany($test1, $test2);
echo $test1 . ', ' . $test2;
You can use func_get_args to also accept a dynamic number of arguments and return a dynamic number of results as well.
Use the global keyword.
<?php
$test = 1;
function addtest() {
global $test;
$test = $test + 1;
}
addtest();
echo $test; // 2
?>
Related
I have code something like this:
<?
$a="localhost";
function body(){
global $a;
echo $a;
}
function head(){
global $a;
echo $a;
}
function footer(){
global $a;
echo $a;
}
?>
is there any way to define the global variable in one place and make the variable $a accessible in all the functions at once? without making use of global $a; more?
The $GLOBALS array can be used instead:
$GLOBALS['a'] = 'localhost';
function body(){
echo $GLOBALS['a'];
}
From the Manual:
An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
If you have a set of functions that need some common variables, a class with properties may be a good choice instead of a global:
class MyTest
{
protected $a;
public function __construct($a)
{
$this->a = $a;
}
public function head()
{
echo $this->a;
}
public function footer()
{
echo $this->a;
}
}
$a = 'localhost';
$obj = new MyTest($a);
If the variable is not going to change you could use define
Example:
define('FOOTER_CONTENT', 'Hello I\'m an awesome footer!');
function footer()
{
echo FOOTER_CONTENT;
}
If a variable is declared outside of a function its already in global scope. So there is no need to declare. But from where you calling this variable must have access to this variable. If you are calling from inside a function you have to use global keyword:
$variable = 5;
function name()
{
global $variable;
$value = $variable + 5;
return $value;
}
Using global keyword outside a function is not an error. If you want to include this file inside a function you can declare the variable as global.
// config.php
global $variable;
$variable = 5;
// other.php
function name()
{
require_once __DIR__ . '/config.php';
}
You can use $GLOBALS as well. It's a superglobal so it has access everywhere.
$GLOBALS['variable'] = 5;
function name()
{
echo $GLOBALS['variable'];
}
Depending on your choice you can choose either.
Add your variables in $GLOBALS super global array like
$GLOBALS['variable'] = 'localhost';
and use it globally as
echo $GLOBALS['variable']
or you can use constant which are accessible throughout the script
define('HOSTNAME', 'localhost');
usage for define (NOTE - without the dollar)
echo HOSTNAME;
This answer is very late but what I do is set a class that holds Booleans, arrays, and integer-initial values as global scope static variables. Any constant strings are defined as such.
define("myconstant", "value");
class globalVars {
static $a = false;
static $b = 0;
static $c = array('first' => 2, 'second' => 5);
}
function test($num) {
if (!globalVars::$a) {
$returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';
globalVars::$a = true;
} else {
$returnVal = 'I forgot';
}
return $returnVal;
}
echo test(9); ---> The value of 9 + 0 + 5 is 14.
echo "<br>";
echo globalVars::$a; ----> 1
The static keywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.
You can try the keyword use in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.
$foo = "New";
$closure = (function($bar) use ($foo) {
echo "$foo $bar";
})("York");
demo |
info
You can declare global variables as static attributes:
class global {
static $foo = "bar";
}
And you can use and modify it every where you like, like:
function echoFoo() {
echo global::$foo;
}
You answered this in the way you wrote the question - use 'define'. but once set, you can't change a define.
Alternatively, there are tricks with a constant in a class, such as class::constant that you can use. You can also make them variable by declaring static properties to the class, with functions to set the static property if you want to change it.
What if you make use of procedural function instead of variable and call them any where as you.
I usually make a collection of configuration values and put them inside a function with return statement. I just include that where I need to make use of global value and call particular function.
function host()
{
return "localhost";
}
$GLOBALS[] is the right solution, but since we're talking about alternatives, a function can also do this job easily:
function capital() {
return my_var() . ' is the capital of Italy';
}
function my_var() {
return 'Rome';
}
I have code something like this:
<?
$a="localhost";
function body(){
global $a;
echo $a;
}
function head(){
global $a;
echo $a;
}
function footer(){
global $a;
echo $a;
}
?>
is there any way to define the global variable in one place and make the variable $a accessible in all the functions at once? without making use of global $a; more?
The $GLOBALS array can be used instead:
$GLOBALS['a'] = 'localhost';
function body(){
echo $GLOBALS['a'];
}
From the Manual:
An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
If you have a set of functions that need some common variables, a class with properties may be a good choice instead of a global:
class MyTest
{
protected $a;
public function __construct($a)
{
$this->a = $a;
}
public function head()
{
echo $this->a;
}
public function footer()
{
echo $this->a;
}
}
$a = 'localhost';
$obj = new MyTest($a);
If the variable is not going to change you could use define
Example:
define('FOOTER_CONTENT', 'Hello I\'m an awesome footer!');
function footer()
{
echo FOOTER_CONTENT;
}
If a variable is declared outside of a function its already in global scope. So there is no need to declare. But from where you calling this variable must have access to this variable. If you are calling from inside a function you have to use global keyword:
$variable = 5;
function name()
{
global $variable;
$value = $variable + 5;
return $value;
}
Using global keyword outside a function is not an error. If you want to include this file inside a function you can declare the variable as global.
// config.php
global $variable;
$variable = 5;
// other.php
function name()
{
require_once __DIR__ . '/config.php';
}
You can use $GLOBALS as well. It's a superglobal so it has access everywhere.
$GLOBALS['variable'] = 5;
function name()
{
echo $GLOBALS['variable'];
}
Depending on your choice you can choose either.
Add your variables in $GLOBALS super global array like
$GLOBALS['variable'] = 'localhost';
and use it globally as
echo $GLOBALS['variable']
or you can use constant which are accessible throughout the script
define('HOSTNAME', 'localhost');
usage for define (NOTE - without the dollar)
echo HOSTNAME;
This answer is very late but what I do is set a class that holds Booleans, arrays, and integer-initial values as global scope static variables. Any constant strings are defined as such.
define("myconstant", "value");
class globalVars {
static $a = false;
static $b = 0;
static $c = array('first' => 2, 'second' => 5);
}
function test($num) {
if (!globalVars::$a) {
$returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';
globalVars::$a = true;
} else {
$returnVal = 'I forgot';
}
return $returnVal;
}
echo test(9); ---> The value of 9 + 0 + 5 is 14.
echo "<br>";
echo globalVars::$a; ----> 1
The static keywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.
You can try the keyword use in Closure functions or Lambdas if this fits your intention... PHP 7.0 though. Not that's its better, but just an alternative.
$foo = "New";
$closure = (function($bar) use ($foo) {
echo "$foo $bar";
})("York");
demo |
info
You can declare global variables as static attributes:
class global {
static $foo = "bar";
}
And you can use and modify it every where you like, like:
function echoFoo() {
echo global::$foo;
}
You answered this in the way you wrote the question - use 'define'. but once set, you can't change a define.
Alternatively, there are tricks with a constant in a class, such as class::constant that you can use. You can also make them variable by declaring static properties to the class, with functions to set the static property if you want to change it.
What if you make use of procedural function instead of variable and call them any where as you.
I usually make a collection of configuration values and put them inside a function with return statement. I just include that where I need to make use of global value and call particular function.
function host()
{
return "localhost";
}
$GLOBALS[] is the right solution, but since we're talking about alternatives, a function can also do this job easily:
function capital() {
return my_var() . ' is the capital of Italy';
}
function my_var() {
return 'Rome';
}
As PHP manual states
Note: You should never use parentheses around your return variable when returning by reference, as this will not work. You can only return variables by reference, not the result of a statement. If you use return ($a); then you're not returning a variable, but the result of the expression ($a) (which is, of course, the value of $a).
I can not understand why not while the following code examples will give the same result.
The code with return $var:
<?php
function a(&$a) {
$a .= "c";
return $a;
}
$b = "b";
echo a($b);
echo $b;
?>
The code with return ($var):
<?php
function a(&$a) {
$a .= "c";
return ($a);
}
$b = "b";
echo a($b);
echo $b;
?>
The examples you show are Passing by Reference, where you pass a reference of a variable to a function. The quote from the manual is about Returning References of a variable in a function.
Just like you can't pass an expression by reference, you can't return an expression by reference, and wrapping a variable in () turns it in to an expression.
Passing a Reference
function a(&$b) { $b = 1; }
$x = 0;
a($x);
echo $x; // echos 1, because a reference to $x was changed
However a(abs($x)); or even a( ($x) ); generates:
Strict Standards: Only variables should be passed by reference
Returning a Reference
class a {
public $c = 0;
public function &b() { return $this->c; }
}
$a = new a;
$x = &$a->b();
$a->c = 1;
echo $x; // echos 1, because $x is a reference to $a->c that was changed
However, return ( $this->c ); generates:
Notice: Only variable references should be returned by reference
The example you give is not about returning references, but is an example of passing references.
function myfunc(&$arg) {
// here $arg has been passed by reference, nothing to do with the docs you quoted
}
The docs are about this:
function & myfunc($arg) {
// here you create your $result using $arg and whatever
return $result; // this will work
return ($result); // this will NOT
}
// and how you use it
$res =& myfunc(1);
You're modifying the variable, because it's passed by reference. But then you're setting it to the value that's returned by the function. That's why you're getting the same result.
When modifying a variable by reference, you don't need to return it. Your function will still have the same result if you write it like this:
function a(&$a) {
$a .= "c";
}
When you pass any value to the function, php copy the value and return a copy, not the variable you passed to the function. So if you want to change value and don't want to return anything from the function you need to declare, functions argument as reference - it means that any variable that you will pass to the function wont be copied by php and manipulation inside the function will change variable outside the function, for example:
$var = 1;
//not reference function
function notReference($argument)
{
$argument++;
}
notReference($var);
echo $var; // you will get 1
function reference(&$argument)
{
$argument++;
}
reference($var)
echo $var; // you will get 2,
I was wondering if it's possible to change and initialize variables in a function without passing arguments to the function. Here is what I want to achieve:
$foo = 'Lorem';
$array = array();
foobar($foo);
function foobar(){
if (strlen($foo)== 1)
$bar = 'Ipsum';
else
$array[] = 'error';
}
fubar();
function fubar(){
if (empty($fouten))
echo $bar;
}
$foo is a local (uninitialized) variable inside a function. It is different from the global variable $foo ($GLOBALS['foo']).
You have two ways:
$foo;
$bar;
$array = array();
function foobar(){
global $foo, $array, $bar;
if (strlen($foo)== 1)
$bar = 'Ipsum';
else
$array[] = 'error';
}
or by using the $GLOBAL array …
This is not really good practice though and will become a maintenance nightmare with all those side effects
Functions in php can be given arguments that have default values. The code you posted as written will give you notices for undefined variables. Instead, you could write:
function foobar($foo = null) {
if($foo) { // a value was passed in for $foo
}
else { // foo is null, no value provided
}
}
Using this function, neither of the below lines will produce a notice
foobar();
foobar('test');
I saw some function declarations like this:
function boo(&$var){
...
}
what does the & character do?
It's a pass by reference. The variable inside the function "points" to the same data as the variable from the calling context.
function foo(&$bar)
{
$bar = 1;
}
$x = 0;
foo($x);
echo $x; // 1
Basically if you change $var inside the function, it gets changed outside. For example:
$var = 2;
function f1(&$param) {
$param = 5;
}
echo $var; //outputs 2
f1($var);
echo $var; //outputs 5
It accepts a reference to a variable as the parameter.
This means that any changes that the function makes to the parameter (eg, $var = "Hi!") will affect the variable passed by the calling function.
It is pass by reference.
If you are familiar with C pointers, it is like passing a pointer to the variable.
Except there is no need to dereference it (like C).
you are passing $var as reference, meaning the actual value of $var gets updated when it is modified inside boo function
example:
function boo(&$var) {
$var = 10;
}
$var = 20;
echo $var; //gets 20
boo($var);
echo $var //gets 10
The ampersand ( & ) before a variable ( & $foo ) overrides pass by value to specify that you want to pass the variable by reference instead.
For example if you have this:
function doStuff($variable) {
$variable++;
}
$foo = 1;
doStuff($foo);
echo $foo;
// output is '1' because you passed the value, but it doesn't alter the original variable
doStuff( &$foo ); // this is deprecated and will throw notices in PHP 5.3+
echo $foo;
// output is '2' because you passed the reference and php will alter the original variable.
It works both ways.
function doStuff( &$variable) {
$variable++;
}
$foo = 1;
doStuff($foo);
echo $foo;
// output is '2' because the declaration of the function requires a reference.
If any function starts with ampersand(&), It means its call by Reference function. It will return a reference to a variable instead of the value.
function reference_function( &$total ){
$extra = $total + 10;
}
$total = 200;
reference_function($total) ;
echo $total; //OutPut 210