This question already has an answer here:
Global variables aren't working as expected with frameworks
(1 answer)
Closed 7 years ago.
According to the PHP variable scope manual in the "The global keyword" section we have the following piece of code:
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
The above script will output 3.
but in my case is echo out 2.
I misunderstand something?
You have to call the Sum() function in order to modify the value of $b. Make sure you call it before you echo. If you encapsulated your $a and $b inside a function or class or namespace, it will not work like in that example.
Related
This question already has answers here:
What does "&" mean in '&$var' in PHP? [duplicate]
(2 answers)
Closed 3 months ago.
<?php
function doSomething( &$arg ){
$return = $arg;
$arg += 1;
return $return;
}
$a = 3;
$b = doSomething( $a );
echo $a.' ';
echo $b;
?>
I know the answer a=4 and b=3 I understand how b= 3 but how come value of the a increased
The & operator tells PHP not to copy the variable when passing it to the function. Instead, a reference to the variable is passed into the function, thus the function modifies the original variable instead of a copy.
Therefore $arg += 1; will increase $a
This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 10 years ago.
I was trying to find this answer on Google, but I guess the symbol & works as some operator, or is just not generally a searchable term for any reason.. anyhow. I saw this code snippet while learning how to create WordPress plugins, so I just need to know what the & means when it precedes a variable that holds a class object.
//Actions and Filters
if (isset($dl_pluginSeries)) {
//Actions
add_action('wp_head', array(&$dl_pluginSeries, 'addHeaderCode'), 1);
//Filters
add_filter('the_content', array(&$dl_pluginSeries, 'addContent'));
}
This will force the variable to be passed by reference. Normally, a hard copy would be created for simple types. This can come handy for large strings (performance gain) or if you want to manipulate the variable without using the return statement, eg:
$a = 1;
function inc(&$input)
{
$input++;
}
inc($a);
echo $a; // 2
Objects will be passed by reference automatically.
If you like to handle a copy over to a function, use
clone $object;
Then, the original object is not altered, eg:
$a = new Obj;
$a->prop = 1;
$b = clone $a;
$b->prop = 2; // $a->prop remains at 1
The ampersand preceding a variable represents a reference to the original, instead of a copy or just the value.
See here: http://www.phpreferencebook.com/samples/php-pass-by-reference/
This passes something by reference instead of value.
See:
http://php.net/manual/en/language.references.php
http://php.net/manual/en/language.references.pass.php
I used it for sending a variable to a function, and have the function change the variable around. After the function is done, I don't need to return the function to the return value and set the new value to my variable.
Example
function fixString(&$str) {
$str = "World";
}
$str = "Hello";
fixString($str);
echo $str; //Outputs World;
Code without the &
function fixString($str) {
$str = "World";
return $str;
}
$str = "Hello";
$str = fixString($str);
echo $str; //Outputs World;
This question already has answers here:
Are there pointers in php?
(9 answers)
Closed 7 years ago.
In C we can use pointer for a function parameter:
test( *text);
function test( *txt){
//codes goes here
}
Is it possible in PHP?
Variable names in PHP start with $ so $entryId is the name of a variable.
$this is a special variable in Object Oriented programming in PHP, which is reference to current object.
-> is used to access an object member (like properties or methods) in PHP, like the syntax in C++.
So your code means this: place the value of variable $entryId into the entryId field (or property) of this object.
The & operator in PHP, means pass reference. Here is an example:
$b=2;
$a=$b;
$a=3;
print $a;
print $b;
// output is 32
$b=2;
$a=&$b; // note the & operator
$a=3;
print $a;
print $b;
// output is 33
In the above code, because we used & operator, a reference to where $b is pointing is stored in $a. So $a is actually a reference to $b.
There is a good explanation of pointers on this page
There are references, but that's not the same as pointers.
php.net has multiple pages explaining What References Are, What References Do and What References Are Not.
There too, it is mentioned multiple times that
References are not pointers.
They provide a way to assign $a to $b so that if you reassign $b, $a changes as well:
$a = 'a';
$b = &$a; // Reference
$b = 'b'; // Now $a == 'b'
This can be used for function arguments as well:
function myFunc(&$b)
{
$b = 'b';
}
$a = 'a';
myFunc($a); // Now $a == 'b'
Before PHP 5.3.0 is was also possible to do a thing called "call-time pass-by-reference", where you would have a "normal" function declaration and use the & operator in the call instead:
function myFunc($b)
{
$b = 'b';
}
$a = 'a';
myFunc(&$a); // As of PHP 5.3.0 produces a Fatal Error, saying:
// Call-time pass-by-reference has been removed; If you would like to pass argument by reference, modify the declaration of myFunc().
But beware! Assigning another reference will not update the original reference:
$a = 'a';
$b = 'b';
$c = &$a;
$c = &$b; // $a == 'a'
[ Demo ]
A trap resulting from that exists with the global keyword.
$a = 'a';
$b = 'b';
function myFunc()
{
global $a, $b;
$a = &$b;
var_dump($a);
}
myFunc(); // 'b'
var_dump($a); // 'a'
That is because global $a effectively means $a = &$GLOBALS['a'], so assigning it a new reference will not update $GLOBALS.
Of course you can prevent that by using $GLOBALS directly.
But if you're using globals at all, you should probably rethink your design anyway.
With references, there is now also a difference between setting a variable = NULL and using unset().
= NULL follows references, unset() does not:
$a = 'a';
$b = &$a;
unset($b); // $a == 'a'
$a = 'a';
$b = &$a;
$b = NULL; // $a == NULL
[ Demo ]
Bottom line:
References allow for things that wouldn't be possible without them, but sometimes do not behave the way one would expect them to, because of how PHP was built.
This question already has answers here:
Why does PHP's call_user_func() function not support passing by reference?
(4 answers)
Closed 8 years ago.
I have:
function increment(&$var)
{
$var++;
}
$a = 0;
call_user_func('increment', $a);
echo $a."\n";
Why does this return:
Warning: Parameter 1 to increment() expected to be a reference, value given in
and $a is still 0. Why is this?
Any references to official documentation would help.
Documentation says "Note: Note that the parameters for call_user_func() are not passed by reference."
You might use call_user_func_array instead.
function increment(&$a) {
$a++;
}
$x = 1;
call_user_func_array("increment", array(&$x));
echo $x;
From the documentation of call_user_func:
Calls the callback given by the first parameter and passes the remaining parameters as arguments.
This is what you want using call_user_func_array instead of call_user_func:
<?php
function increment(&$var)
{
$var++;
}
$a = 0;
call_user_func_array("increment", array(&$a));
echo $a."\n";
This is my setting:
display_startup_errors = on
display_errors = On
error_reporting = E_ALL | E_STRICT
$b;
function func ($name) {
global $b;
$b = 10;
return $b;
}
$a =& func("myname");
++$a ;
echo '<br/>$a= '.$a.' $b= ' .$b."<br/>";
xdebug_debug_zval('a'); echo "<br/> ";
The above code output's the following notice:
Strict standards: Only variables should be assigned by reference in /path/to/file/file.php on line 'some line number'
$a= 11 $b= 10
a: (refcount=1, is_ref=0)=11
Why is the above code displaying the notice? And why is there a C.O.W (copy on write) taking place?
$b;
function &func ($name) {//change here: to return a reference.
global $b;
$b = 10;
return $b;
}
$a =& func("myname");
++$a ;
echo '<br/>$a= '.$a.' $b= ' .$b."<br/>";
xdebug_debug_zval('a'); echo "<br/> ";
The above code will output:
$a= 11 $b= 11
a: (refcount=1, is_ref=1)=11
Why is no strict standards notice thrown here? And here the reference works.
$b;
function &func ($name) {
global $b;
$b = 10;
return $b;
}
$a = func("myname"); //change here: removed &
++$a ;
echo '<br/>$a= '.$a.' $b= ' .$b."<br/>";
xdebug_debug_zval('a'); echo "<br/> ";
The above code will output:
$a= 11 $b= 10
a: (refcount=1, is_ref=0)=11
Why does a C.O.W take place here?
For info on xdebug_debug_zval visit here.
& operator in PHP as reference is removed in the recent versions. Specially from PHP5.
Now all reference type data (class etc) are automatically passed by reference.
Read Returning References and Passing by Reference
Your second snippet is working correctly.
In PHP if you want to return by reference, you have to write use & operator in definition as well while assigning. see PHP reference Doc. Therefore, 2nd has correct syntax and it is working without giving any warning.
First snippet is giving warning as you haven't defined that this function will be returning reference and still you are assigning its return value by reference. So, it will not work. (see a's value is incremented to 11 but b is 10 only.)
In Third snippet you aren't assigning reference so it is not giving any warning. (But because of this reference will not work. (see difference in a's and b's value)
How the hell did I miss this: This completely mutes my question!
from Returning References at PHP manual
Note: If you try to return a reference from a function with the syntax: return ($this->value); this will not work as you are attempting to return the result of an expression, and not a variable, by reference. You can only return variables by reference from a function - nothing else. Since PHP 4.4.0 in the PHP 4 branch, and PHP 5.1.0 in the PHP 5 branch, an E_NOTICE error is issued if the code tries to return a dynamic expression or a result of the new operator.
To use the returned reference, you must use reference assigment:
<?php
function &collector() {
static $collection = array();
return $collection;
}
$collection = &collector();
$collection[] = 'foo';
?>