PHP 使用抽象 class 还是接口?

PHP use abstract class or interface?

在这段代码中,使用抽象类代替接口更好,还是像现在这样好?如果是,为什么?

/** contract for all flyable vehicles **/
interface iFlyable {
    public function fly();
}

/* concrete implementations of iFlyable interface */
class JumboJet implements iFlyable {
    public function fly() {
        return "Flying 747!";
    }
}

class FighterJet implements iFlyable {
    public function fly() {
        return "Flying an F22!";
    }
}

class PrivateJet implements iFlyable {
    public function fly() {
        return "Flying a Lear Jet!";
    }
}

/** contract for conrete Factory **/
/**
* "Define an interface for creating an object, but let the classes that implement the interface
* decide which class to instantiate. The Factory method lets a class defer instantiation to
* subclasses."
**/
interface iFlyableFactory {
    public static function create( $flyableVehicle );
}

/** concrete factory **/
class JetFactory implements iFlyableFactory {
    /* list of available products that this specific factory makes */
    private  static $products = array( 'JumboJet', 'FighterJet', 'PrivateJet' );

    public  static function create( $flyableVehicle ) {
        if( in_array( $flyableVehicle, JetFactory::$products ) ) {
            return new $flyableVehicle;
        } else {
            throw new Exception( 'Jet not found' );
        }
    }
}

$militaryJet = JetFactory::create( 'FighterJet' );
$privateJet = JetFactory::create( 'PrivateJet' );
$commercialJet = JetFactory::create( 'JumboJet' );

界面更加灵活。这样,并不是所有会飞的东西都被迫从同一个基础继承class(php不支持多重继承)

所以

class bird extends animal implements flyable
class plane extends machine implements flyable
class cloud implements flyable

有时不需要灵活性。

抽象 classes 还可以提供函数定义,如果多个飞行 classes 需要相同的 fly() 方法,这将减少代码重复

希望能帮助您理解您的选择