开发者

Calling member function from other member function in PHP?

开发者 https://www.devze.com 2023-04-09 20:08 出处:网络
I\'m a little confused about the situation shown in this code... class DirEnt { public function PopulateDirectory($path)

I'm a little confused about the situation shown in this code...

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.
    }
}

Why do I need to use either $this->push_back(new Som开发者_Go百科eClass($file, $dtype)) or self::push_back(new SomeClass($file, $dtype)) to call the member function push_back? I can't seem to access it just by doing push_back(new SomeClass($file, $dtype)) like I would have expected. I read When to use self over $this? but it didn't answer why I need one of them at all (or if I do at all, maybe I messed something else up).

Why is this specification required when the members are both non-static and in the same class? Shouldn't all member functions be visible and known from other member functions in the same class?

PS: It works fine with $this-> and self:: but says the functions unknown when neither is present on the push_back call.


$this->push_back will call the method as part of the CURRENT object.

self::push_back calls the method as a static, which means you can't use $this within push_back.

push_back() by itself will attempt to call a push-back function from the global scope, not the push_back in your object. It is not an "object call", it's just a plain-jane function call, just as calling printf or is_readable() within an object calls the usual core PHP functions.


I cant seem to access it just by doing push_back(new SomeClass($file, $dtype)) like I would have expected.

This way you call push_back() as a function. There is no way around $this (for object methods) or self::/static:: (for class methods), because it would result into ambiguity

Just remember: PHP is not Java ;)


You can access like this

public static function abc($process_id){
return 1;
}
public static function xyz(){
$myflag=self::abc();
return $myflag;
}
output : 1
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号