dptn69182
2013-09-03 22:18
浏览 23
已采纳

PHP分在类方法中使用全局变量[关闭]

i am trying to make $var1 to work on many different method

var1 is outcome of extract() from an array that 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 any way to fix it??

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doujiao8491 2013-09-03 22:23
    已采纳

    2 ways to fix it:

    First, the best - passing variables as function arguments:

    $var1 = 'something';
    
    class myClass{
        function doSomething($var){
            echo $var;
        }
    }
    
    $obj = new myClass(); //You could also pass it to constructor
    $obj->doSomething($var1);
    

    Second, working, but is considered to be a bad practice:

    $var1 = 'something';
    
    class myClass{
        function doSomething(){
            global $var1 ;
            echo $var1;
        }
    }
    
    $obj = new myClass();
    $obj->doSomething();
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题