接口和类

时间:2016-12-21 11:07:45

标签: php class interface polymorphism

我想知道PHP中是否有可能代码:

interfaces In{}
class Cl implements In{}

In $var = new Cl();

2 个答案:

答案 0 :(得分:0)

接口可以像这样使用。     

// Declare the interface 'iTemplate'
interface iTemplate
{
    public function setVariable($name, $var);
    public function getHtml($template);
}

// Implement the interface
class Template implements iTemplate
{
    private $vars = array();

    public function setVariable($name, $var)
    {
        $this->vars[$name] = $var;
    }

    public function getHtml($template)
    {
        foreach($this->vars as $name => $value) {
            $template = str_replace('{' . $name . '}', $value, $template);
        }

        return $template;
    }
}

参考:http://php.net/manual/en/language.oop5.interfaces.php

答案 1 :(得分:0)

是的,你可以:

<?php
interface In{}
class Cl implements In{}

$var = new Cl();
var_dump($var);
echo ($var instanceof In)?'Yes $var implements In':'No $var doesn\'t implements In';
echo "\n";
echo ($var instanceof Cl)?'Yes $var implements Cl':'No $var doesn\'t implements Cl';

将输出:

  

对象(Cl)#1(0){}

     

是$ var实现在

     

是$ var实现Cl

Here is a sandbox to try yourself

Here is the documentation about interfaces

如果您询问多态性,可以使用Traits:

<?php
trait Hello {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait World {
    public function sayWorld() {
        echo 'World';
    }
}

class MyHelloWorld {
    use Hello, World;
    public function sayExclamationMark() {
        echo '!';
    }
}

$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();
?>

Here is a sandbox to test it

Here is the documentation about traits