This question already has answers here:
How does the "&" operator work in a PHP function?
(4 answers)
Closed 9 years ago.
I've been looking everywhere for a satisfactory answer to this. Still not wrapping my head around the usefulness of the & character when used as a reference. Why would I want to use it? I learn best by example.
Here is an example taken from php.net with slight modification:
<?php
function foo(&$var)
{
$showVar = $var++;
echo $showVar;
}
$a=5;
foo($a);
?>
How is the above different from:
<?php
function foo($var) // & was removed here.
{
$showVar = $var++;
echo $showVar;
}
$a=5;
foo($a);
?>
I got the same exact result (the value of 5) when printing $var++, but according to the documentation there, it should be 6.
What is the advantage?
In any case, I'd appreciate a very lucid and even dumbed down explanation of that the benefits of using & is when referencing something.
Best to explain with code:
function foo(&$var)
{
$var++;
}
$a=5;
foo($a);
echo $a; // 6
In this example above the value of $a can changed insed the function. Meaning if you pass by reference the function has access to a variable in the calling context. This is different to:
function foo($var)
{
$var++;
}
$a=5;
foo($a);
echo $a; // 5
Where the param passed to the function is just a copy of the value of $a
The difference is that if you don't pass it by reference, the change only happens locally within the function.
In your first scenario, if you use echo $a after calling the function, you'll see the changes made to that variable within the function. In the second scenario, you wont.
Related
This question already has answers here:
Stop using `global` in PHP
(6 answers)
Closed 7 years ago.
The $GLOBALS array of PHP provides access to all global variables, like
<?php
$foo = 'hello';
function myFunc() {
echo $GLOBALS['foo']; // prints "hello"
}
?>
Now I have to work on some code from other people that directly adds elements to the array to have it available globally (without having an according variable), like so:
<?php
function doSomething() {
// $newData is NOT existing anywhere!
$GLOBALS['newData'] = 'Hello World!';
// now $GLOBALS['newData'] is available anywhere else w/o actual variable
}
?>
Until now I never saw this specific usage of the $GLOBALS array and was wondering if it is considered "safe" or "good"? The PHP manual makes no statement about writing to this array, only about reading from it.
Opinion perhaps, but I would think it's better instead to use define instead of the $GLOBALS array if you're looking to define a constant for use in other parts of your application.
PHP:define - Manual
<?php
function doSomething() {
$_POST['__newData'] = 'Hello World!';
}
doSomething();
echo $_POST['__newData'];
?>
This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 9 years ago.
The below code is for sanitizing the posted values. Can some tell me What is the difference between,
<?php
function sanitize_data(&$value, $key) {
$value = strip_tags($value);
}
array_walk($_POST['keyword'],"sanitize_data");
?>
and
<?php
function sanitize_data($value, $key) {
$value = strip_tags($value);
}
array_walk($_POST['keyword'],"sanitize_data");
?>
Thanks
The first uses value as a refrence, so any time you call it with some variable the variable will be changed in the outer scope, not only in the function itself.
Look in the manual for 'reference' if you want more info.
It's called 'pass by reference'. &$value will relate to the original $value passed into the function by pointer, rather than working on a function version.
Please see the PHP Manual.
The first function the value of the first parameter is passed by reference and in the second not. If the variable is passed by referenced, changes to it will also be done on the value outside of the function scope (in the scope you call the function).
Also read the PHP documentation (pass by reference) and is also demonstrated on the array_walk doc page.
First method is called as "Passing value as reference".
So $_POST array values are changed .
In second method will not change the value of $_POST
You can check SO Link: Great Explanation about it.
https://stackoverflow.com/a/2157816/270037
The first function gets $value passed by reference so it can modify it directly, the second function gets passed $value's value.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Parse error on explode('-','foo-bar')[0] (for instance)
In PHP there are functions that return an array, for example:
$a = parse_url("https://stackoverflow.com/q/9461027/87015");
echo $a["host"]; // stackoverflow.com
My question is how to combine the above two statements into a single statement. This (is something that works in JavaScript but) does not work:
echo parse_url("https://stackoverflow.com/q/9461027/87015")["host"];
Note: function array dereferencing is available since PHP 5.4; the above code works as-is.
You can do a little trick instead, write a simple function
function readArr($array, $index) {
return $array[$index];
}
Then use it like this
echo readArr(parse_url("http://stackoverflow.com/questions/9458303/how-can-i-change-the-color-white-from-a-uiimage-to-transparent"),"host");
Honestly, the best way of writing your above code is:
$a = parse_url("http://stackoverflow.com/q/9461027/87015");
echo $a["scheme"];
echo $a["host"];
Isn't that what I originally posted?
Yes. Depending on context you may want a better name than $a (perhaps $url), but that is the best way to write it. Adding a function is not an attractive option because when you revisit your code or when someone reads your code, they have to find the obscure function and figure out why on earth it exists. Leave it in the native language in this case.
Alternate code:
You can, however, combine the echo statements:
$a = parse_url("http://stackoverflow.com/q/9461027/87015");
echo $a['scheme'], $a['host'];
This question already has answers here:
PHP syntax for dereferencing function result
(22 answers)
Closed 9 years ago.
I want to do something like this without using extra variables:
class className {
public static function func(){
return array('true','val2');
}
}
if(className::func()[0]) {
echo 'doğru';
} else {
echo 'Yanlış';
}
className::func()[0] is called array dereferencing, and is not valid syntax in all PHP versions. It will be is available starting in PHP 5.4, currently in beta, released March 2012. For earlier PHP version, you will need to use an extra variable somewhere to store the array returned from className::func().
See the PHP 5.4 Array documentation for implementation details.
Array Deferencing is not currently available in PHP. It is on the table for PHP 5.4.
Until then, you would need the extra variable:
$arr = className::func();
if($arr[0]){
echo 'doğru';
}else{
echo 'Yanlış';
}
Well,you can return an object in your method instead.
something like:
class className{
public static function func(){
return (object)array('true'=>'true','val2'=>'val2');
}
}
echo className::func()->true;//Extra variables go away =)
As the others noted, you currently cannot do it this way. If you really cannot use an temporary variable (although I don't see a reason not to use one) you could use
if(current(className::func())) // or next() or reset()
But make sure you read the documentation about these functions to treat empty arrays properly.
Reference: current
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Reference - What does this symbol mean in PHP?
Can anyone explain this experssion
&variablename in PHP.
I have seen this around at many places but i am not able to figure out what does this statement do.
Thanks in advance
J
PHP reference. References in PHP are a means to access the same variable content by different names. There are three operations performed using references: assigning by reference, passing by reference, and returning by reference.
PHP reference
for example:
$example1 = 'something';
$example2 =& $example1;
echo("example 1: $example1 | example 2: $example2\n"); //example 1: something | example 2: something
$example1 = 'nothing'; //change example 1 to nothing
echo("example 1: $example1 | example 2: $example2"); //example 1: nothing | example 2: nothing
You can pass variable to function by reference, so that function could modify its arguments. The syntax is as follows:
<?php
function foo(&$var)
{
$var++;
}
$a=5;
foo($a);
// $a is 6 here
?>
taken from http://www.phpbuilder.com/manual/language.references.pass.php