<?php
class t{
public function e(){
echo "class";
}
}
$t = new t();
function getCity(){
$t->e();
}
getCity();
?>这样子调用为什么会出错, $t在函内部变成局部对象? 也没听说过 global 对象
如果我要在函数内调用已new的对象 怎么调用 难不成只能重新new一次?

解决方案 »

  1.   

    把 $t 当成变量传递给 方法 getCity();function getCity($obj)
    {
       $obj->e();
    }getCity($t);
      

  2.   

    除楼上方法还可以加个global关键字,这样就会把$t识别成全局变量了,否则确实会当成局部变量的。$t = new t();
    function getCity(){
        global $t;
        $t->e();
    }
    getCity();
      

  3.   

    你是 C 程序员吧???class t{
        public function e(){
            echo "class";
        }
    }function getCity(){
        $t = new t();
        $t->e();
    }
    getCity();
    见手册:变量的作用范围