milan
milan

Reputation: 2219

php multiple classes and methods with same name

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

Upvotes: 0

Views: 1410

Answers (2)

dev-null-dweller
dev-null-dweller

Reputation: 29462

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.

Upvotes: 2

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143061

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.

Upvotes: 2

Related Questions