Just started learning PHP, and while experimenting with variable scopes, I created this code:
<?php
$x = 5;
function scopeTest($x) {
global $x;
echo $x;
}
scopeTest(4);
?>
In the given function I pass value 4, in the function that value is stored in variable $x (local to the function). The output of this code is 5 and not 4.
I don't know where the variable with value 4 gone? I know I can do this by changing the local variable name in the function but I want to know flow of this program, how it is outputting 5.
Is the local variable $x overridden with the global variable $x?
Is there any way to access the local variable $x value 4 within the function?
The local variable is being overwritten with the statement global and since they are sharing the same variable name, you lost reference to it.
But by doing this, you can use both:
$x = 5;
function scopeTest($x) {
echo $GLOBALS['x'], $x; // 54
}
scopeTest(4);
Or.. just rename the local variable
function scopeTest($y) {
global $x;
echo $x, $y;
}
Yes You can use the value 4 of the $x by echoing the $x before the global $x;
global $x; //replace the value of $x to it's global value.
Related
I saw this on W3Schools.
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
The output is 0, 1 and 2.
I wonder why it is not 0, 0 and 0.
Since each time the function is called, the variable x becomes 0 again.
I am a PHP beginner. Thanks!
If you declare a var static inside a function, the var keep it value over multiple calls. You could compare it to a static var inside of classes.
The code you post is a good example to see the actual effect. However I would only carefull use static inside functions, because most of the time, you need the static value somewhere else, reset the value, or something else which requires to much logic and makes the code really bad.
A good example would be a function, which returns a unique identifier for a given identifier. This could be simply achieved by using this code.
function unique_id($id) {
static $count = 0;
return $id . ($id++);
}
This example may clarify. static has a scope, thus is not a global variable. So I can define static $x outside the function and it will be defined there. Since static has scope, it wouldn't make any sense to keep on executing and resetting $x = 0. So, php will only acknowledge it the first time that line is called.
<?php
static $x = 1000;
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
<?php
function sum($y) {
$y = $y + 5;
}
$x = 5;
sum($x);
echo $x;
?>
So I have this code. The questions are: What does it output? The answer: 5. How do I make it to output 10? The answer: sum(&$x).
The problem is that I don't understand why the answer to the first question is 5. When you make sum($x), shouldn't it replace the function with $x, so $x= 5+5=10? Why the answer is 5? I really don't understand. Someone explaind me something related to pointers and the adress, but I didn't understand. I never understood the concept of pointers, and I googled it and apparently there are no pointers in php, so I'm super confused. My friend said that a variable is formed of a value, and the memory adress of that value. Can someone explain me like I'm 5 years old why the answer is 5 and not 10? Please
Let's pretend $x is a piece of paper with 5 written on it.
function sum($y) {
$y = $y + 5;
}
Here $y is the value of what you have written. You add 5 to such value in your mind, but the note is left untouched.
function sum(&$y) {
$y = $y + 5;
}
With the reference operator (&$y), you pass the very paper to the function, and it overwrites what's written on it.
For primitive values like numbers, I wouldn't bother and always return the value you want:
function valuePlusFive($x) {
return $x + 5;
}
$x = 5;
$x = valuePlusFive($x);
This is not a very good explanation from theory point of view, but this should help you understand the concept:
when you declare function like this and then call it:
function ($argument) {...}
The argument you pass there is passed by value. This means that inside the scope of a function you will be working with a copy of an argument you passed. You can imagine that before the function is called the copy of argument has been made and inside the function you're working with the copy, while original remains untouched. Once the function is finished the copy is no more
However when you declare it like this:
function (&$argument) {...}
You are passing argument by reference, meaning that you are working directly with a variable you've passed. So in this case no copies are made, you took the argument from one place, put it inside the function and changed it.
In PHP, "The scope of a variable is the context within which it is defined." (according to the docs). So inside your function, $y (a copy of the value you passed in) is being operated on, but it is not returned by the function. So when the function ends, the value is no longer accessible outside the function.
If you want to pass the variable in by reference (similar to a pointer in C) then you can add a & like so:
function sum(&$y) {
$y = $y + 5;
}
Now when you call this code:
$x = 5;
sum($x);
echo $x;
it will output 10. Maybe a better way to do this would be to return a value from your function, and output that value:
function sum($y) {
return $y + 5;
}
$x = 5;
echo sum($x);
(1) I want to know what is the difference between call by value and call by reference in php. PHP works on call by value or call by reference?
(2) And also i want to know that do you mean by $$ sign in php
For example:-
$a = 'name';
$$a = "Paul";
echo $name;
output is Paul
As above example what do u mean by $$ on PHP.
$$a = b; in PHP means "take the value of $a, and set the variable whose name is that value to equal b".
In other words:
$foo = "bar";
$$foo = "baz";
echo $bar; // outputs 'baz'
But yeah, take a look at the PHP symbol reference.
As for call by value/reference - the primary difference between the two is whether or not you're able to modify the original items that were used to call the function. See:
function increment_value($y) {
$y++;
echo $y;
}
function increment_reference(&$y) {
$y++;
echo $y;
}
$x = 1;
increment_value($x); // prints '2'
echo $x; // prints '1'
increment_reference($x); // prints '2'
echo $x; // prints '2'
Notice how the value of $x isn't changed by increment_value(), but is changed by increment_reference().
As demonstrated here, whether call-by-value or call-by-reference is used depends on the definition of the function being called; the default when declaring your own functions is call-by-value (but you can specify call-by-reference via the & sigil).
Let's define a function:
function f($a) {
$a++;
echo "inside function: " . $a;
}
Now let's try calling it by value(normally we do this):
$x = 1;
f($x);
echo "outside function: " . $x;
//inside function: 2
//outside function: 1
Now let's re-define the function to pass variable by reference:
function f(&$a) {
$a++;
echo "inside function: " . $a;
}
and calling it again.
$x = 1;
f($x);
echo "outside function: " . $x;
//inside function: 2
//outside function: 2
You can pass a variable by reference to a function so the function can modify the variable.
More info here.
Call by value: Passing the variable value directly and it will not affect any global variable.
Call by reference: Passing the address of a variable and it will affect the variable.
It means $($a), so its the same as $name (Since $a = 'name'). More explanation here What does $$ (dollar dollar or double dollar) mean in PHP?
Call by value means passing the value directly to a function. The called function uses the value in a local variable; any changes to it do not affect the source variable.
Call by reference means passing the address of a variable where the actual value is stored. The called function uses the value stored in the passed address; any changes to it do affect the source variable.
If you have an if statement like this:
<?php
$a = 1;
$b = 2;
if ($a < $b) {
$c = $a+$b;
}
?>
Would you be able to access the $c variable outside of the if statement like so:
<?php
$a = 1;
$b = 2;
if ($a < $b) {
$c = $a+$b;
}
echo $c
?>
In PHP, if doesn't have its own scope. So yes, if you define something inside the if statement or inside the block, then it will be available just as if you defined it outside (assuming, of course, the code inside the block or inside the if statement gets to run).
To illustrate:
if (true) { $a = 5; } var_dump($a == 5); // true
The condition evaluates to true, so the code inside the block gets run. The variable $a gets defined.
if (false) { $b = 5; } var_dump(isset($b)); // false
The condition evaluates to false, so the code inside the block doesn't get to run. The variable $b will not be defined.
if ($c = 5) { } var_dump($c == 5); // true
The code inside the condition gets to run and $c gets defined as 5 ($c = 5). Even though the assignment happens inside the if statement, the value does survive outside, because if has no scope. Same thing happens with for, just like in, for example, for ($i = 0, $i < 5; ++$i). The $i will survive outside the for loop, because for has no scope either.
if (false && $d = 5) { } var_dump(isset($d)); // false
false short circuits and the execution does not arrive at $d = 5, so the $d variable will not be defined.
For more about the PHP scope, read the variable scope manual page.
PHP's scope is completely function-based. It's not the same as C or Java where it's local to what block that variables are nested in.
For PHP's scope:
// Global variable
$a = 0;
function f()
{
// Cannot be accessed outside of f()
if (true)
$b = 0;
// However, it can still be accessed anywhere in f()
$b += 1;
}
If you want a variable to be global, simply use the global keyword:
// Global variable
$a = 0;
function f()
{
// Use $a from global scope
global $a;
// Modifies global $a
$a += 1;
}
function g()
{
// Use $b from global scope, even though it hasn't been defined yet
global $b;
// Can be accessed outside of g()
$b = 0;
// Cannot be accessed outside of g(); this $a "shadows" the global version
// The global $a is still 0
$a = 1;
}
If the if statement containing the variable was executed, then yes, you can access the variable outside of the if statement. Here's a thought on why it works that way. In many programming languages you can "declare" a variable before you use it, just to let the compiler know that it's there. For example in Java you can declare an 'int', then use it like so:
int number;
if(true)
number = 5;
In Java, you have to declare a variable like this before using it in an if-then statement. In php, however, there isn't really a way to do that. Since php is dynamically typed, you can't write int $number. In Java, the computer allocates a 32 bit block of memory (the size of an int) when the variable is declared. In php, I believe, the memory is not allocated until something is actually stored in the variable. The best equivalent to 'declaring' a php variable I could think of would just be to write:
$number; //This is NOT needed
if(true)
$number = 5;
But when you look at the code, it seems kind of strange to just write $number like that. I think the computer would think it was equally strange because as I said before, it is a dynamically typed language, and so it doesn't need to allocate a whole chunk of memory for the number. So you can just leave it like this:
if(true)
$number = 5;
Depends.
In PHP chances are yes it would, although of course, if a isnt < b, then c wont exist when you get to the echo c line and your code will complain.
However, in most languages this wouldnt compile for that reason
The value of a local variable of a function has to be retained over multiple calls to the function. How should that variable be declared in PHP?
using static. example:
function staticDemo() {
static $x =1;
echo $x;
$x++;
}
the variable $x gets that static value the first time the function is called, afterwards it retains it's state.
example:
staticDemo(); // prints 1
staticDemo(); // prints 2
staticDemo(); // prints 3
Just FYI:
function globalDemo() {
global $x;
echo $x;
$x++;
}
globalDemo(); // prints ''
globalDemo(); // prints 1
globalDemo(); // prints 2
globalDemo(); // prints 3