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
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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.