0

If I call "myClass::getItems()" from the "workingCLass" which getId method will be called? The one that echos "hello" or "bye"? Thank you.

class myClass extends otherClass {
   function getId(){
      echo "hello";
   }
}


class otherClass{
   function getItems(){
      $this->getId();
   }
   function getId(){
      echo "bye";
   }
}


class workingClass extends myClass {
   function __construct(){
      $this->getItems();
   }
}

2 Answers 2

2

The one with "hello", because you explicitly specified which one to call.

The problem, though, is that it's not static and you call it in a static context.

EDIT: With $this, it will not call anything, because there's no getItems() in the workingClass. If workingClass extended the otherClass it would do the "bye" thingie.

Sign up to request clarification or add additional context in comments.

1 Comment

Your right, it should say $this->getItems(). If I did not have the "getId" method in "myClass", would it echo "bye"?
2

This will result in fatal error, since you are calling this method statically (::) and inside this method you are using $this special variable, that refers to workingClass(object from which it was called) and workingClass has no getId method.

OK, now after fixing the example I can say that it will output 'hello', because when calling method from the object ($this->) PHP will always run one defined in latest child class.

4 Comments

Yea your right, I messed up in my example, I am looking at someone code and did not want to copy paste a ton of stuff.
it will still be fatal error... If workingClass will extend myClass then it will work and will call getId() from myClass (hello).
@milan - now this example make sense, I've updated my answer with some explanation.
"PHP will always run one defined in latest child class", that is what I did not know. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.