Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling member function from other member function in PHP?

Tags:

methods

php

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 SomeClass($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.

like image 666
John Humphreys Avatar asked Oct 02 '11 20:10

John Humphreys


1 Answers

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 ;)

like image 187
KingCrunch Avatar answered Oct 19 '22 12:10

KingCrunch