Jump to content

Calling method of parent class


mkaminski

Recommended Posts

Hello,

Say I have a class such as this..

class A
{
public function sayHello()
{
  print("hello");
}
}

class B extends A
{
public function sayHello()
{
  print("A more refined hello...perhaps bonjour?");
}
}

$object = new b();

Now $object is of type B. Calling $object->sayHello() would output "A more refined hello...perhaps bonjour?"

Now how can I call the sayHello() so that it will call the A class' sayHello() method, simply outputting "hello"? I know how to do this in Java...it would just be a simple type cast... but how can this be done in PHP 5? I want to change the type of the object, not do a parent::sayHello() in class B's sayHello() method.

Thanks!
Link to comment
https://forums.phpfreaks.com/topic/20340-calling-method-of-parent-class/
Share on other sites

you can create an access method in class b

class B extends A
{
  /// your stuff

  function A_Hello()
  {
      parent::sayHello();
  }
}

For a non invasive means, if A's sayHello method doesn't involve any class variables, you can say

A::sayHello();

But the first is probaly a safer bet for anything non-trivial, and deffinitely for any method that uses class variables (instance variable).  Sometimes Global class variables will be okay.

So, the absolute safest way is the first one.  Use that if at all possible.

Jeff

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.