php中的类中的类
以下是问题提纲:php中的类中的类,php,class,object,Php,Class,Object,以下是问题提纲: /*First object*/ class MYCLASS { /*Some Properties and methods*/ public function foo() { $this->somevar = 'yes'; $this->display = '<tag>' . $this->
/*First object*/
class MYCLASS {
/*Some Properties and methods*/
public function foo() {
$this->somevar = 'yes';
$this->display = '<tag>' . $this->somevar . '</tag>';
/*NOTICE this line, not using return, but echo*/
echo $this->display;
}
}
/*Second object, instantiating first object inside*/
class NEXTCLASS {
/*Some Properties and methods*/
public function yoo() {
$this->maa = new MYCLASS;
return '123' . $this->maa->foo() . '456';
}
}
/*Show output*/
$next = new NEXTCLASS;
echo $next->yoo();
/*第一个对象*/
类MYCLASS{
/*一些性质和方法*/
公共功能foo(){
$this->somevar='yes';
$this->display='.$this->somevar';
/*注意这一行,不是使用return,而是echo*/
echo$this->display;
}
}
/*第二个对象,实例化内部的第一个对象*/
下一类{
/*一些性质和方法*/
公共职能yoo(){
$this->maa=新MYCLASS;
返回'123'。$this->maa->foo()'456';
}
}
/*显示输出*/
$next=新的NEXTCLASS;
echo$next->yoo();
这应该输出123yes456
,但它显示的是yes123456
我认为$this->maa->foo()
是一个对象,这就是为什么它在字符串之前打印。获得2个相关链接:
问题是:在不更改
MYCLASS
的情况下,我可以在NEXTCLASS
中以任何方式更改$this->maa->foo()
吗?在您的代码中,您有以下内容:
/*NOTICE this line, not using return, but echo*/
echo $this->display;
你的评论其实有答案。使用返回:
return $this->display;
您的输出将是:
123<tag>yes</tag>456
123是456
如果立即回显,将首先打印该标记,然后打印字符串的其余部分。或者,如果您确实反对在此处使用return,您可以尝试使用输出缓冲。您可以使用输出缓冲区
public function yoo() {
ob_start();
$this->maa = new MYCLASS;
$this->maa->foo();
$buffer = ob_get_flush();
ob_end_clean();
return '123' . $buffer . '456';
}
为了执行
return '123' . $this->maa->foo() . '456`;
它首先必须调用$this->maa->foo()
。在该方法内部,它响应yes
。然后它返回NULL
(因为没有return
语句)yoo
然后将其连接起来,以便执行
return '123' . NULL . '456';
返回字符串123456
最后,$next->yoo()
的调用者回显该字符串
YOU可以在yoo()
中执行以下操作:
您可以使用ob\u XXX
函数捕获输出。您正在MYCLASS
中执行输出。该输出将在NEXTCLASS
中的连接有机会执行之前执行。感谢@Barmar,现在我了解了编程和计算机科学之间的区别。我只学了第一个。
public function yoo() {
ob_flush();
ob_start();
$this->maa = new MYCLASS;
$this->maa->foo();
$temp = ob_get_clean();
ob_end_clean();
return '123' . $temp . '456';
}