我有这样的类,我想把变量放在外面(我猜是返回),这样我就能用它做点什么了。
class MyClass{
private function MyPrivate(){
$rows = 'SomeVar';
echo $rows.' is echoed from inside';
//return $rows;
return $this->rows;
}
function Foo(){
$this->MyPrivate();
//$this->rows;
}
//return $rows;
//return $this->rows;
}
$myclass = new MyClass;
$myclass->Foo();
//$myclass->rows;
echo '<br />';
echo $rows.'is echoed from outside';
在类内部回显私有函数中的变量是可行的,但是在外部回显变量就不行了。注释掉的代码是我想要达到的效果。我没有做这个类,所以我不想弄乱它,也不想改变它里面的任何东西,因为我担心它会把事情搞砸。
这是我的输出:
SomeVar is echoed from inside
is echoed from outside
如您所见,在第二个实例中没有SomeVar(变量)。不过,我很惊讶它还能工作。在过去的两天里,我一直在网上阅读文档和教程,但这个问题需要尽快解决,这就是为什么我发了这篇文章。请帮帮忙。谢谢。
发布于 2011-12-02 16:31:49
使用return
语句时,应将其赋值给变量。此外,您应该返回$rows
,而不是$this->rows
,因为它们实际上是不同的变量:
class MyClass{
private function MyPrivate(){
$rows = 'SomeVar';
echo $rows.' is echoed from inside';
return $rows;
}
function Foo(){
return $this->MyPrivate();
}
}
$myclass = new MyClass;
$rows = $myclass->Foo();
echo '<br />';
echo $rows.'is echoed from outside';
发布于 2011-12-02 16:42:01
你确实应该在你的类中显式声明你的变量。此外,没有理由担心从不同的函数返回行-只需使其成为您的类的成员,将其可见性设置为public,并在您的类内外访问它。
看起来您还混淆了函数中的局部变量和类成员变量。您必须始终使用$this->
来访问该类的成员。
<?php
class MyClass
{
public $rows;
private function MyPrivate()
{
$this->rows = "Low-level programming is good for the programmer's soul --J. Carmack";
echo $this->rows . ' is echoed from inside';
}
function Foo()
{
$this->MyPrivate();
}
}
$obj = new MyClass;
$obj->Foo();
echo $obj->rows . ' is echoed from outside.';
发布于 2011-12-02 16:32:44
你可以这样做:
class MyClass{
private function MyPrivate(){
$rows = 'SomeVar';
echo $rows.' is echoed from inside';
//return $rows;
return $rows;
}
function Foo(){
return $this->MyPrivate();
//$this->rows;
}
//return $rows;
//return $this->rows;
}
$myclass = new MyClass;
$rows = $myclass->Foo();
//$myclass->rows;
echo '<br />';
echo $rows.'is echoed from outside';
https://stackoverflow.com/questions/8359431
复制相似问题