convert local variable to global variable in php

1 min



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.



Like it? Share with your friends!

Junaid Rehman

I am a blogger and freelance web developer by profession. I love to blog and learn new things about programming and IT World.