0

Say I have a protected method in PHP, as shown below:

class Test {

    protected function hello($x) {
        echo "hello " . $x . "<br>";
    }

    public function __construct() {
        $i = 2;
        self::hello($i);
        $this::hello($i);
    }
}

$test = new Test();

The output is hello 2 printed twice. So calling the protected method hello works via both self and $this. Which is the correct approach? My personal answer is self, since $this refers to the current object, and any object of this class shouldn't have access to its protected method. Am I right or wrong?

Edit: This question isn't a duplicate. The other question talks only about accessing static members members through self and $this. I am interested in protected members specifically.

lebowski
  • 1,031
  • 2
  • 20
  • 37
  • @puelo That question and its answers talk only about accessing static members through self and $this. Not protected members. – lebowski Jul 29 '17 at 19:03
  • Use $this->hello(). $this refers to the instance of Test. You would only want to use self:: when working with polymorphism – aknosis Jul 29 '17 at 19:07
  • Protected function is available to call in a class consructor. – u_mulder Jul 29 '17 at 19:07
  • @Aknosis But aren't protected methods not accessible through instances of the class? That's why I think using $this doesn't make sense. Am I wrong? – lebowski Jul 29 '17 at 19:17
  • @lebowski All methods/fields are accessible to the class itself (private, protected, or public). They are not accessible outside of the class. (e.g. you can't do $test->hello(), but from inside the class you can do $this->hello(); – aknosis Jul 30 '17 at 23:36

0 Answers0