Pergunta

do I have something wrong in my code or I really cannot implement interface in the abstract class? My code is not working and PHP throws an error:

Fatal error: Class 'Blah' not found

My code:

interface IBlah {
  public function Fun();
}

abstract class Blah implements IBlah {
  public function FunCommon() {
    /* CODE */
  }

  abstract public function Fun();
}

class Koko extends Blah {
  public function Fun() {
    /* CODE */
  }
}

When I'll change my code to following, now it works:

abstract class Blah {
  public function FunGeneral() {
    /* CODE */
  }

  abstract public function Fun();
}

Am I doing anything wrong? Thank you very much.

EDIT: 2014-04-01

I'm sorry @raina77ow, I was too rash. Your answer is correct and it helped me very much - I understood interface x abstract class and your advice will be really helpful in the future (my +1 for you still remains), but I tried it on another machine. Today, when I came to work and I apply your advice, the error still showed up.

I'd like to give you additional information. At the first, I removed "abstract public function Fun();" from my abstract class according to your advice. The second thing is that my interface and abstract class are in one PHP file and class Koko is in another one (if I move class Koko into the same file as interface and abstract class, no error is thrown).

I tried to print declared interfaces - get_declared_interfaces(), and declared classes - get_declared_classes(), and interface IBlah is printed out, but nor Blah neither Koko are printed out.
And When I change declaration of abstract class implementing interface only to abstract class (as I described above), Iblah and Blah and Koko are printed out all of them.

Foi útil?

Solução

There's no need declaring an abstract function in an abstract class that's already declared in the interface it implements - you'll get an error (in PHP 5.2, looks like PHP 5.3 treats it a bit differently):

Can't inherit abstract function IBlah::Fun() (previously declared abstract in Blah)

Solution: just drop this declaration from an abstract class altogether - this...

interface IBlah {
  public function Fun();
}

abstract class Blah implements IBlah {
  public function FunCommon() {}
}

class Koko extends Blah {
  public function Fun() {}
}

... is a valid code both in PHP 5.2 and PHP 5.3, and Koko objects will be treated as IBlah ones. That's easy to check:

function t(IBlah $blah) {
  var_dump($blah);
}

t(new Koko()); // object(Koko)#1 (0) {}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top