zaimazhar's avatar

Accessing parent method from subclass instantiation

Hi.

I tried to access a parent method from a subclass instantiation using this code;

test_obj3.php

abstract class AchievementType {
    protected $user;

    public function uppercaseName() {
        return strtoupper($this->user);
    }
}

class bestAnswer extends AchievementType {
    public function awarded($user) {
        $this->user = $user;
    }
}

var_dump((new bestAnswer())->awarded("zaimazhar97")->uppercaseName());

After the awarded method retrieved the value "zaimazhar97", shouldn't $this->user variable is accessible from both classes?

but I got

Fatal error: Uncaught Error: Call to a member function uppercaseName()

I thought the subclass bestAnswer inherits uppsercaseName() method from the parent? Sorry if the question is simple...

Thank you for you time. 🙂

1 like
3 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@zaimazhar You just add return $this; in your awarded() method. That should work.

public function awarded($user) {
        $this->user = $user;

        return $this;
    }
5 likes
zaimazhar's avatar

Ahh, since I am chaining the method, uppercaseName() expects a returning value from awarded() method, isn't it? How did I missed such small detail. 😅

Thanks.

4 likes

Please or to participate in this conversation.