This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Reference assignment operator in php =&
$var2 = $var1;
$var2 = &$var1;
Example:
$GLOBALS['a']=1;
function test()
{
global $a;
$local=2;
$a=&$local;
}
test();
echo $a;
Why is $a still 1 ?
The operator =& works with references and not values.
The difference between $var2=$var1 and $var2=&$var1 is visible in this case :
$var1 = 1;
$var2 = $var1;
$var1 = 2;
echo $var1 . " " . $var2; // Prints '2 1'
$var1 = 1;
$var2 =& $var1;
$var1 = 2;
echo $var1 . " " . $var2; // Prints '2 2'
When you use the =& operator you don't say to $var2 "take the value of $var1 now" instead you say something like "Your value will be stored at the exact same place that the value of $var1".
So anytime you change the content of $var1 or $var2, you will see the modification in the two variables.
For more informations look on PHP.net
EDIT :
For the global part, you'll need to use $GLOBALS["a"] =& $local; Cf. documentation.
When you do $var2 = $var1, PHP creates a copy of $var1, and places it in $var2. However, if you do $var2 = &$var1, no copy is made. Instead, PHP makes $var2 point at $var1 - what this means is that you end up with two variables that point at the exact same thing.
An example:
$var1 = "Foo";
$var2 = $var1; // NORMAL assignment - $var1's value is copied into $var2
$var3 = &$var1; // NOT normal copy!
echo $var2; // Prints "Foo".
echo $var3; // Also prints "Foo".
$var1 = "Bar"; // Change $var1.
echo $var2; // Prints "Foo" as before.
echo $var3; // Now prints "Bar"!
global $a;
This is equivalent to:
$a = &$GLOBALS['a'];
When you assign $a a new reference, you're changing $a and not $GLOBALS['a'].
What do you expect to be output below?
$GLOBALS['a']=1;
function test()
{
$a='foobar'; // $a is a normal variable
$a=&$GLOBALS['a']; // same as: global $a;
$local=2;
$a=&$local;
}
test();
echo $a;
Related
How could I access specific parameter from a function, example:
function someFunction()
{ echo $a = 7;
echo $b = 70;
}
someFunction();//770
How can I return only $a or $b, is possible ?
echo vs return
First of all, I think it is important to note that echo and return have very different behaviors and are used in very different contexts. echo simply outputs whatever is passed to it, either to an html page, or to the server log.
<?php
$a = 5;
function printFoo() {
echo 'foo';
}
echo '<h1>Hello World!</h1>'; // prints an h1 tag to the page
echo $a; // prints 5 to the page
foo(); // prints foo to the page
?>
return on the other hand is used to "[end] execution of the current function, and return its argument as the value of the function call." return can only ever take one argument. It can also only be executed once in a function; once it is reached, the code will jump out of the function back to where the function was invoked.
<?php
function getFoo() {
return 'foo';
}
// print the value returned by getFoo() directly
echo getFoo();
// store it in a variable to be used elsewhere
$foo = getFoo(); // $foo is now equal to the string 'foo'
function getFooBar() {
return 'foobar'; // code beyond this statement will not be executed
echo 'something something';
return 'another foobar';
}
echo getFooBar(); // prints 'foobar'
?>
function paramters
As it stands, someFunction can only return $a or $b or an array containing $a and $b, which may become a problem if, say, you need to print out $c. To make the function more reusable, you can pass it an argument and then reuse the function wherever you like.
<?php
function printSomething($myVar) {
echo $myVar;
}
$a = 7;
$b = 70;
$c = 770;
printSomething($a) . '\n';
printSomething($b) . '\n';
printSomething($c) . '\n';
printSomething(7000); // you don't have to pass it a variable!
// Output:
// 7
// 70
// 700
// 7000
?>
If you wish to return only one parameter then you just use the return statement.
<?php
function someFunction()
{
$a = 7;
$b = 70;
return [$a, $b];
}
$arrayS = someFunction();//array containing $a and $b
echo $arrayS[0]."\n";
echo $arrayS[1]."\n";
echo "\n";
echo "Another way to access variables\n";
echo someFunction()[0]."\n";
echo someFunction()[1]."\n";
I want to initialise a variable with the contents of another variable, or a predefined value, if said other variable is not set.
I know I could use
if(isset($var1)){
$var2 = $var1;
} else{
$var2 = "predefined value";
}
I thought doing it like this would be more elegant:
$var2 = $var1 || "predefined value";
Last time I checked, this did work (or my memory is fooling me). But here, when I print $var2, it is always 1. It seems PHP checks if the statement $var1 || "predefined value" is true and assigns 1 to $var2.
I want "predefined value" to be assigned to $var2, in case $var1 doesn't exist.
Any peculiarity of PHP I'm missing here to make this work?
Thanks in advance
I generally create a helper function like this:
function issetor(&$var, $def = false) {
return isset($var) ? $var : $def;
}
and call it with the reference of the variable :
$var2 = issetor($var1, "predefined");
I just read that in PHP 7, there will be a new abbreviation for
$c = ($a === NULL) ? $b : $a;
It will look like this:
$c = $a ?? $b;
And can be extended like this:
$c = $a ?? $b ?? $c ?? $d;
explanation: $c will be assigned the first value from the left, which is not NULL.
function my_function() {
$var1 = "123";
$var2 = "abc";
return $var1;
}
Sometimes I want to use $var2 but calling my_function() will simply return what the function returns ( $var1 ).
Is there any trick to retrieve the $var2 data ? maybe my_function($var2) ..
Regards.
Just pass the arguments by reference, e.g.
$var1 = "";
$var2 = "";
function my_function(&$var1, &$var2) {
//^ ^ See here
$var1 = "123";
$var2 = "abc";
}
my_function($var1, $var2);
//Now you can use $var1 and $var2 for you next function with the new values.
And if you want to read more about references in general see the manual: http://php.net/manual/en/language.references.php
Another alternative is declaring $var2 as a global inside the function.
$var2 = "hello";
function my_function() {
global $var2;
$var1 = "123";
$var2 = "abc";
return $var1;
}
Now my_function() will be able to access $var2 declared outside its scope and change its value.
$var1 = '321';
echo $var1; // will be '321' obviously
$myVar = my_function();
function my_function()
{
$var1 = '123';
return $var1;
}
echo $var1; // will be '321'
echo $myVar; // will be '123';
Read more: http://php.net/manual/en/language.variables.scope.php
Is there another way of writing something like this?
$var2 = ($var1) ? $var1 : 'bar';
Example..
$var1 = 'foo';
$var2 = ($var1) ? $var1 : 'bar';
echo $var2; //Outputs foo
$var1 = false;
$var2 = ($var1) ? $var1 : 'bar';
echo $var2; //Outputs bar
I hoped
$var2 = $var1 || 'bar';
would work because I thought I've seen that before but it didn't. Any ideas?
Thanks!
$var2 = $var1 ?: 'bar';
New since PHP 5.3. http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
Almost correct. Since PHP 5.3 (I believe) there is a new construct:
<?php
$foo = false;
$foo = $foo ?: 'bar';
echo $foo; // $foo is now "bar".
There is not prior to PHP 5.3.
If compatability to pre-5.3 versions of PHP is important I suggest making a method;
function b($a, $b) { return $a?$a:$b; }
B for best, as well as being short.
Usage:
echo b($username, "Not logged in");
Using PHP 5 I would like to know if it is possible for a variable to dynamically reference the value
of multiple variables?
For example
<?php
$var = "hello";
$var2 = " earth";
$var3 = $var.$var2 ;
echo $var3; // hello earth
Now if I change either $var or $var2 I would like $var3 to be updated too.
$var2 =" world";
echo $var3;
This still prints hello earth, but I would like to print "hello world" now :(
Is there any way to achieve this?
No, there is no way to do this in PHP with simple variables. If you wanted to do something like this in PHP, what you'd probably do would be to create a class with member variables for var1 and var2, and then have a method that would give you a calculated value for var3.
This should do the trick. I tested it on PHP 5.3 and it worked. Should also work on any 5.2.x version.
You could easily extend this with an "add"-Method to allow an arbitrary number of strings to be placed in the object.
<?php
class MagicString {
private $references = array();
public function __construct(&$var1, &$var2)
{
$this->references[] = &$var1;
$this->references[] = &$var2;
}
public function __toString()
{
$str = '';
foreach ($this->references as $ref) {
$str .= $ref;
}
return $str;
}
}
$var1 = 'Hello ';
$var2 = 'Earth';
$magic = new MagicString($var1, $var2);
echo "$magic\n"; //puts out 'Hello Earth'
$var2 = 'World';
echo "$magic\n"; //puts out 'Hello World'
No. Cannot be done without utilizing some sort of custom String class.
Check the PHP manual for types and variables, especially this passage:
By default, variables are always
assigned by value. That is to say,
when you assign an expression to a
variable, the entire value of the
original expression is copied into the
destination variable. This means, for
instance, that after assigning one
variable's value to another, changing
one of those variables will have no
effect on the other. For more
information on this kind of
assignment, see the chapter on
Expressions.
it's a bit late, but it's interesting question.
You could do it this way:
$var = "hello";
$var2 = " earth";
$var3 = &$var;
$var4 = &$var2;
echo $var3.$var4; // hello earth
From my point of view the following code is a little closer to the required:
$a = 'a';
$b = 'b';
$c = function() use (&$a, &$b) { return $a.$b; };
echo $c(); // ab
$b = 'c';
echo $c(); // ac
Create a function.
function foobar($1, $2){
$3 = "$1 $2";
return $3;
}
echo foobar("hello", "earth");
echo foobar("goodbye", "jupiter");