从PHP中的其他成员函数调用成员函数?

Joh*_*0te 9 php methods

我对这段代码中显示的情况感到有点困惑......

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.
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么我需要使用$this->push_back(new SomeClass($file, $dtype))self::push_back(new SomeClass($file, $dtype))调用成员函数push_back?我似乎无法push_back(new SomeClass($file, $dtype))像我期望的那样访问它.我读过什么时候使用自我超过$ this?但它没有回答为什么我需要其中一个(或者如果我一直这样做,也许我搞砸了别的东西).

当成员是非静态成员并且在同一个类中时,为什么需要此规范?不应该从同一个类中的其他成员函数中看到并知道所有成员函数吗?

PS:它可以很好地工作$this->,self::但是当电话中没有这些功能时,这些功能都是未知的push_back.

Mar*_*c B 8

$this->push_back 将该方法作为CURRENT对象的一部分调用.

self::push_back将该方法称为静态,这意味着您无法$this在push_back中使用.

push_back()它本身将尝试从全局范围调用回推函数,而不是对象中的push_back.它不是一个"对象调用",它只是一个简单的函数调用,就像调用printfis_readable()在一个对象中调用通常的核心PHP函数一样.


Kin*_*nch 7

我似乎无法push_back(new SomeClass($file, $dtype))像我期望的那样访问它.

这样你就可以调用push_back()函数了.没有办法$this(对于对象方法)或self::/ static::(对于类方法),因为它会导致歧义

请记住:PHP不是Java;)