Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP can't extend from interface?

I write below in a single php file.

<?php
interface people
{
    public function take($s);
}

class engineer extends people
{
    public function take($s){
        echo $s;
    }
}
?>

The people is an interface, the engineer extends people. But when I run this code, the error:

Fatal error: Class engineer cannot extend from interface people in E:\php5\Mywwwroot\b.php on line 12

What's happened? My PHP version is 5.4.

like image 981
roast_soul Avatar asked Sep 16 '13 14:09

roast_soul


People also ask

Can interface be extended in PHP?

Interfaces can be extended like classes using the extends operator.

Can you use extends with interface?

Yes. One interface can inherit another by use of the keyword extends. The syntax is the same as for inheriting classes. When a class implements an interface that inherits another interface, it must provide implementations for all methods defined within the interface inheritance chain.

Does PHP support interface?

A PHP interface defines a contract which a class must fulfill. If a PHP class is a blueprint for objects, an interface is a blueprint for classes. Any class implementing a given interface can be expected to have the same behavior in terms of what can be called, how it can be called, and what will be returned.

Can PHP class extend two classes?

Classes, case classes, objects, and traits can all extend no more than one class but can extend multiple traits at the same time.


3 Answers

You implement interfaces and extend classes:

<?php
interface people
{
    public function take($s);
}

class engineer implements people
{
    public function take($s){
        echo $s;
    }
}
?>
like image 108
John Conde Avatar answered Oct 19 '22 05:10

John Conde


extends is for extending another class.

For interfaces, you need to use implements instead.

(An interface can extend another interface, though)

like image 43
Spudley Avatar answered Oct 19 '22 04:10

Spudley


Depends on what you want, it could be:

  • class extends aClass
  • class implements anInterface
  • interface extends anInterface

You can extend only one class/interface and implement many interfaces. You can extend interface to another interface, e.g. interface DieselEngineInterface extends EngineInterface.

Also want to note a comment, now that you can have class and interface hierarchy, you need to know when to use them.

like image 25
imel96 Avatar answered Oct 19 '22 04:10

imel96