PHP 用接口来改善PHP的代码结构

simuel · 2019-11-27 18:11:05 · 热度: 17
  1. 上一节介绍了 PHP 的接口,这里来看看如何更好地使用这个OOP特性。

interface Fruit
{
    const MAX_WEIGHT = 5;   //此处不用声明,就是一个静态常量
    function setName($name);
    static function getName() {
    }
}

class Apple implements Fruit
{
}

通过implements来实现一个接口时,只需要写出抽象方法,不需要给出具体实现,否则将会如下报错:

Fatal error: Interface function User::getName() cannot contain body。

看一下正确的php接口实现:

<?php
interface Fruit
{
    const MAX_WEIGHT = 5;   //此处不用声明,就是一个静态常量
    function setName($name);
    function getName();
}
//实现接口
class Apple implements Fruit
{
    private $name;
    function getName() {
        return $this->name;
    }
    function setName($_name) {
        $this->name = $_name;
    }
}

$apple = new Apple(); //创建对象
$apple->setName("苹果");
echo "创建了一个" . $apple->getName();
echo "<br />";
echo "MAX_WEIGHT is " . Apple::MAX_WEIGHT;   //静态常量
?>

// 程序输出
// 创建了一个苹果
// MAX_WEIGHT is 5

PHP还可以实现多个接口,一个类可以实现多个接口。只要使用 , 将多个接口链接起来就可以。

<?php
interface Fruit
{
    const MAX_WEIGHT = 5;   //此处不用声明,就是一个静态常量
    function setName($name);
    function getName();
}

interface Food
{
    function dilicious();
}

//实现接口
class Apple implements Fruit, Food
{
    private $name;
    function getName() {
        return $this->name;
    }
    function setName($_name) {
        $this->name = $_name;
    }
    function dilicious() {
        echo '好吃';
    }
}

$apple = new Apple(); //创建对象
$apple->setName("苹果");
echo "创建了一个" . $apple->getName();
echo $apple->dilicious();
echo "<br />";
echo "MAX_WEIGHT is " . Apple::MAX_WEIGHT;   //静态常量
?>

PHP还可以继承并实现接口:

interface Fruit
{
    const MAX_WEIGHT = 5;   //此处不用声明,就是一个静态常量
    function setName($name);
    function getName();
}

interface Food
{
    function dilicious();
}

class FoodObjects
{

}

//实现接口
class Apple extends FoodObjects implements Fruit, Food
{
    private $name;
    function getName() {
        return $this->name;
    }
    function setName($_name) {
        $this->name = $_name;
    }
    function dilicious() {
        echo '好吃';
    }
}

当我们明白了接口以及工厂的意义时,可以写一下下面的代码,一个数据库操作为例子:

<?php
interface PersonProvider
{
    public function getPerson($givenName, $familyName);
}

class DBPersonProvider implements PersonProvider
{
    public function getPerson($givenName, $familyName)
    {
        /* pretend to go to the database, get the person... */
        $person = new Person();
        $person->setPrefix("Mr.");
        $person->setGivenName("John");
        return $person;
    }
}

class PersonProviderFactory
{
    public static function createProvider($type)
    {
        if ($type == 'database')
        {
            return new DBPersonProvider();
        } else {
            return new NullProvider();
        }
    }
}

$config = 'database';
/* I need to get person data... */
$provider = PersonProviderFactory::createProvider($config);
$person = $provider->getPerson("John", "Doe");

echo($person->getPrefix());
echo($person->getGivenName());
?>

猜你喜欢:
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册