+15 votes
757 views
in Programming by (3.1k points)
 
I'm writing a function in PHP , but I try to use certain variables and seems to not exist. Are variables that I created outside the function and I would like to use within the function , but without passing them as a parameter.
 Answer by Miguel Angel Alvarez In PHP, within a function, in principle, there are only variables you have created within it. Thus , it is normal that you can not access variables created outside there that function.
 
 
 
 
In PHP , variables declared externally to a function are global and created in a function are local variables. However, PHP provides us with a couple of mechanisms for within functions can use global variables. The ? Global? Array $ GLOBALS and the declaration of global variables ? at the beginning of the function.
 
 
 
 
All the field variables and the use of global variables inside a function are explained in our manual PHP.

3 Answers

+14 votes
by (8.1k points)
You only need to declare the variable as global within the function example 
 
<? 
variable $ = "whatever"; 
function A () 
{
Global variable $;/ / here you tell php to look for the variable $ Variable globlar 
$ variable = "value change" ;/ / Here change the value of the global variable $ value 
function B () 
{
variable $ = "hello" ;/ / this is a variable local to the function B, if not modified modified global variable. 
 
>
+5 votes
by (18.3k points)
That's one way to solve the problem, another method is needed to pass the variables as parameters of the function when the same call. 
 
Sample function call: 
nombredefuncio ($ variable1, $ variable2, $ variable) 
 
You can pass any number of varying only thing is that when you develop the function should ask you the same amount of variables that you send. 
 
Example development function: 
 
nombredefuncio function ($ variable1, $ variable2, $ variable) 
{
.... 
}
+6 votes
by (18.3k points)
wave have the same question, there's something I do not understand: I use the following code on the screen but nothing is displayed ... just goes Parse error, then I put the (instruction;) and I do not get error but not displayed screen. 
in the php manual example shows that sin (;) copy it and paste it in my notepad + + store in www is the folder where I keep my pages using wamp server ... 
 
 
 
<? php 
 
$ myvar = "foo"; 
otravariable = $ 1234; 
function myfunction () {
global $ myvar, $ otravariable / / with this line inside the function, declare the use of global variables 
echo $ myvar; 
echo $ otravariable; 
 
 
 
 
<? php 
 
$ myvar = "foo"; 
otravariable = $ 1234; 
function myfunction () {
global $ myvar, $ otravariable;/ / with this line inside the function, declare the use of global variables 
echo $ myvar; 
echo $ otravariable; 
 
>
Ask a Question
Welcome to WikiTechSolutions where you can ask questions and receive answers from other members of the community.

You can ask a question without registration.

Categories

...