Error: Global Variable is not accessable to local function

0 votes

hii,

I'm having an error when variable $x is accessed by function myTest. Can someone let me know how can i used global varaible?

<?php
$x = 5; // global scope

function myTest() {
    // using x inside this function will generate an error
    echo "<p>Variable x inside function is: $x</p>";
}
myTest();

echo "<p>Variable x outside function is: $x</p>";
?>
Feb 19 in PHP by kartik
• 4,380 points
24 views

1 answer to this question.

0 votes

Hey kartik,

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:

The global keyword is used to access a global variable from within a function.

To do this, use the global keyword before the variables (inside the function):

Example:

<?php
$x = 5;
$y = 10;

function myTest() {
    global $x, $y;
    $y = $x + $y;
}

myTest();
echo $y; // outputs 15
?>
answered Feb 19 by Niroj
• 8,220 points

Related Questions In PHP

0 votes
1 answer

What is Php Mysql Database? How php connect to database?

Hello kartik, MySQL is the most popular database ...READ MORE

answered Feb 25 in PHP by Dey
62 views
0 votes
1 answer

What is meant by passing the variable by value and reference in PHP?

Hello, When the variable is passed as value ...READ MORE

answered 6 days ago in PHP by Niroj
• 8,220 points
15 views
0 votes
1 answer

What is the use of $_REQUEST variable in php?

Hii @kartik, The $_REQUEST variable is used to read the ...READ MORE

answered 6 days ago in PHP by Niroj
• 8,220 points
27 views
0 votes
1 answer

Error:“Notice: Undefined variable”, “Notice: Undefined index”, and “Notice: Undefined offset” using PHP

Hello @kartik, The best way for getting input string is: $value ...READ MORE

answered 1 day ago in PHP by Niroj
• 8,220 points
4 views
+1 vote
1 answer

What is the relationship between angularjs Scope with controller/view?

Let us consider the below block: <div ng-controller="emp"> ...READ MORE

answered Jan 20 in Web Development by Niroj
• 8,220 points

edited Jan 21 by Niroj 49 views
0 votes
1 answer

What is data binding in AngularJS?

Data binding is synchronization of data between the ...READ MORE

answered Jan 23 in Web Development by Niroj
• 8,220 points
33 views
0 votes
1 answer

How can we avoid my php form from hacking?

Hii @kartik, If you want to know php ...READ MORE

answered Feb 13 in PHP by Niroj
• 8,220 points
40 views
0 votes
1 answer

How can you display the error messages?

Hey, In the HTML form, we add ...READ MORE

answered Feb 13 in PHP by Niroj
• 8,220 points
33 views
0 votes
1 answer

How to check if php session is already started or not?

Hello kartik, Use session_id(), it returns an empty string ...READ MORE

answered 1 day ago in PHP by Niroj
• 8,220 points
3 views
0 votes
1 answer

What is a Cookie? How to create Cookies With PHP?

A cookie is often used to identify ...READ MORE

answered Feb 13 in PHP by Niroj
• 8,220 points
53 views