+ 6
PHP - why I can't get the variable $name ?
Hello everyone :) In the course "variable scope", there is this code (posted bellow) but I don't understand why the course say that $name is not accesible in the function if it's a global variable (this is exactly what the course say : "This script will produce an error, as the $name variable has a global scope, and is not accessible within the getName() function.") Because if I right understand global variable, it's can be accesed from everywhere, not only in a specific function (?). <?php $name = 'David'; function getName() { echo $name; } getName(); // Error: Undefined variable: name ?>
10 Antworten
+ 9
You can assign it into the global array
$GLOBALS["name"] = "David";
Or use global keyword inside the function before using it
$name = 'David';
function getName() {
global $name;
echo $name;
}
+ 5
Thank's for you answer !
So, by default the function is "local" in a specific variable. But, if I precise "global" in front of $name I could access to it everywhere (even in my variable) ?
+ 3
In function instead of calling as $name call as
$GLOBALS['name'];
+ 2
it will be better if you use OOP programming
class User{
private $name;
public function setName($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}
}
//using class
$user = new User;
$user->setName('David');
echo $user->getName();
+ 2
thank you
+ 1
To use a variable in PHP you put it as
$GLOBALS[“name”] = “David”;
+ 1
Donald Faulknor $name in this example is a global variable. It's in the $GLOBALS array just as $_POST, $_SERVER, and the other superglobals are in the $GLOBALS array.
Take a look at this code to see this more clearly.
https://code.sololearn.com/wnj8d35bQJJM/?ref=app
0
$name has to be defined within the function to use it in the function. On another note $name is not a global variable. $_POST is an example of a global variable. You might be confusing global variable with prefefined variable or reserved keyword; however, $name is neither. $name is free to use however you want withing the rules of variables.
0
you most write:$this->getName();
and this variable defind $global
0
no,int bihaend