Home  >  Article  >  Backend Development  >  构造函数问题???

构造函数问题???

WBOY
WBOYOriginal
2016-06-23 14:14:33834browse

大概情况是这样的,B类方法里面大量用到A类的对象实例,于是我在B类构造函数里面直接实例化A类

class A{public $mes="ok";}class B{public function __construct(){//下面很多方法都要用到A的对象,于是我在B类构造方法里面直接对象一个,方便下面调用$a=new A();} //下面B的成员方法开始调用A对象的方法public function test(){$mes=$a->mes;  //代码运行到这里提示$a不知道是个什么东西,即没有实例化,但上我在构造函数中不是做了吗?好像没有起作用echo $mes;}$b=new B();$b->test();}



我在B的构造函数中实例化的A对象,B的成员方法不能用,怎么回事呢?后面我有很多成员方法都是要用a对象啊,不可能一个一个的去实例化哦。


回复讨论(解决方案)

变量的作用域问题
$this->a = new A();
$mes = $this->a->mes;

上面运行结果提示:

Notice: Undefined variable: a in C:\php\apache\htdocs\test.php on line 18

Notice: Trying to get property of non-object in C:\php\apache\htdocs\test.php on line 18

变量的作用域问题
$this->a = new A();
$mes = $this->a->mes;

牛!一语道破天机!感谢!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn