convert local variable to global variable in php



Suppose you have a variable which has same name as declared within the function and outside the function. But that variable has different scope. If the variable is declared within the function then it is called local variable and if it declared outside the function then it is global variable.

local variable vs global variable
local variable vs global variable

If we assign/change the value in local variable it does not effect global variable. So we have to make local variable behave as global variable. The easy way to do this is to write global in front of local variable. See the code below:-

<?php
class Person
{
	var $name;
	function set_name($data){
		global $name;
		$name = $data;	
	}
	function get_name(){
		global $name;
		return $name;	
	}
}
?>

In the code above i have write global in front of $name to make it global. Now if we change the value of $name within the function then it effects the global variable also.


Comments 0

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

convert local variable to global variable in php

log in

reset password

Back to
log in