Calling a member function from another member function in PHP?

I am a little confused by 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 $this->push_back(new SomeClass($file, $dtype)) or self::push_back(new SomeClass($file, $dtype)) to call the push_back member function? It seems I cannot access it just by doing push_back(new SomeClass($file, $dtype)) as I expected. I read When to use self over $ this? but he didn’t answer why I need one of them at all (or if I do at all, maybe I ruined something else up).

Why is this specification needed when members are non-stationary and are in the same class? Should all member functions be visible and known from other member functions in the same class?

PS: it works fine with $this-> and self:: , but talks about unknown functions when none of them are present in the push_back call.

+8
methods php
source share
2 answers

I cannot access it just by doing push_back(new SomeClass($file, $dtype)) as I 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), as this will lead to ambiguity

Just remember: PHP is not Java;)

+6
source share

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

self::push_back calls the method as static, which means you cannot use $this in push_back.

push_back() will itself try to call the push-back function from the global scope, not the push_back in your object. This is not a "call to an object", it is just a call to a "simple" function, just like calling printf or is_readable() inside an object calls ordinary PHP core functions.

+7
source share

All Articles