-2

I'm new to php, and cannot understand the logic below.

<?php
$user = "abc";
function test(){
$user = "def";
echo $user;
}
function test_2(){
$user = "xyz";
return $user;
}
echo $user;
echo "<br />";
test();
echo "<br />";
echo test_2();
echo "<br />";
echo $user;
?>

When "echo-ing" $user, function test_2() overwrites the value of $user and prints "xyz". But when I simply echo $user [after echo test_2() ], but it prints "abc"; I mean it should again print "xyz" as object $user stores the value "xyz". Can you please explain how does the functions mechanism works here.

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Vaibhav Sidapara
  • 159
  • 2
  • 12
  • possible duplicate of [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](http://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – Lanting Jan 20 '15 at 10:18
  • http://php.net/manual/en/language.variables.scope.php – Quentin Jan 20 '15 at 10:18

3 Answers3

0

This exercise shows that the variable $user is confined to it's scope. For instance in the scope of test() the variable $user is "def", and in the scope of test_2() the variable $user is "xyz".

Samuel Gray
  • 119
  • 1
  • 5
0

In very basic words - the reason is because your functions are not returning back any values. Thats why your variable $user is not changing and it is remaining with the same value as defined in the beginning. Functions are separate operations which act in their own environment"

Hope this helps

0

Php is a loosely coupled language. it means you dont need to declare datatype and as well in runtime u can change the value of the instance. the first $user will print as "abc". once u called the test() function it will assign value "def" to $user. hence u returned the $user so the test() will gives the reslt as "def". when u r calling test2() function the above steps will continue and it will return the value as "xyz".