Jump to content


Photo

Calling method of parent class


  • Please log in to reply
3 replies to this topic

#1 mkaminski

mkaminski
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 11 September 2006 - 02:46 AM

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!


#2 perezf

perezf
  • Members
  • PipPipPip
  • Advanced Member
  • 301 posts
  • LocationFort Lauderdale

Posted 11 September 2006 - 03:34 AM

just type
sayhello();

#3 mkaminski

mkaminski
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 11 September 2006 - 03:36 AM

sorry I dont think that will do it

#4 jefkin

jefkin
  • Members
  • PipPipPip
  • Advanced Member
  • 55 posts

Posted 11 September 2006 - 04:29 AM

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






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users