PHP cent use global variable in class method -
i trying make $var1
work on many different method
var1
outcome of extract()
array contains url parts
exp:
$url = 'localhost/site/classname/edit/254/...';
$arr[var1] = 'edit';
$arr[var2] = '254';
$var1 = 'something'; class myclass{ function dosomething(){ echo $var1; } } $obj = new myclass(); $obj->dosomething();
output:
notice: undefined variable: var1 in....
is there way fix it??
2 ways fix it:
first, best - passing variables function arguments:
$var1 = 'something'; class myclass{ function dosomething($var){ echo $var; } } $obj = new myclass(); //you pass constructor $obj->dosomething($var1);
second, working, considered bad practice:
$var1 = 'something'; class myclass{ function dosomething(){ global $var1 ; echo $var1; } } $obj = new myclass(); $obj->dosomething();
Comments
Post a Comment