我对这段代码中显示的情况有点困惑......
class DirEnt
{
public function PopulateDirectory($path)
{
/*... code ...*/
while ($file = readdir($folder))
{
is_dir($file) ? $dtype = DType::Folder : $dtype = Dtype::File;
$this->push_back(new SomeClass($file, $dtype));
}
/*... code ...*/
}
//Element inserter.
public function push_back($element)
{
//Insert the element.
}
}
为什么我需要使用 $this->push_back(new SomeClass($file, $dtype))
或 self::push_back(new SomeClass($file, $dtype) ))
调用成员函数push_back
?我似乎无法像我预期的那样通过 push_back(new SomeClass($file, $dtype))
访问它。我读了When to use self over $this?但它没有回答我为什么需要其中一个(或者如果我需要,也许我搞砸了其他事情)。
当成员都是非静态成员并且在同一个类中时,为什么需要这个规范?难道不是所有成员函数都应该对同一类中的其他成员函数可见和已知吗?
PS:它与 $this->
和 self::
一起工作正常,但是当 push_back
上都不存在时,它会说函数未知打电话。
最佳答案
$this->push_back
将调用该方法作为 CURRENT 对象的一部分。
self::push_back
将方法作为静态调用,这意味着您不能在 push_back 中使用 $this
。
push_back()
本身将尝试从全局范围调用推回函数,而不是对象中的 push_back。它不是“对象调用”,它只是一个简单的函数调用,就像在对象中调用 printf
或 is_readable()
调用通常的核心 PHP 函数一样。
关于php - 从 PHP 中的其他成员函数调用成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7628921/