第二次作业

2017-10-14  本文已影响0人  玉玉玉_b166

继承与多态
代码:

<?php
abstract class Animal
{
    abstract public function roar();

    public function speak()
    {
        echo "I can speak!\n";
    }

}
class Pig extends Animal
{
    public function roar()
    {
        echo "roar as pig\n";
    }
    public function speak()
    {
        parent::speak();
        echo "I am pig\n";
    }
}

class Dog extends Animal
{
    public function roar()
    {
        echo "roar as dog\n";
    }
    public function speak()
    {
        parent::speak();
        echo "I am dog\n";
    }
}

class Monkey extends Animal
{
    public function roar()
    {
        echo "roar as monkey\n";
    }
    public function speak()
    {
        parent::speak();
        echo "I am monkey\n";

    }
}
function test(Animal $animal)
{
    $animal->roar();
    $animal->speak();
}
test(new Pig());
test(new Dog());
test(new Monkey());
?>

运行:

image.png

接口
代码:

<?php
interface iTalkable
{
    function talk();
}
interface iPlayable
{
    function play();
}
abstract class People implements iTalkable,iPlayable
{
    abstract public function talk();
    abstract public function play();
}
class teacher extends People implements iTalkable,iPlayable
{
    public function talk()
    {
        echo "Least said,soonest mended.\n";
    }
    public function play()
    {
       echo "play less to learn more.\n";
    }
}
$teacher = new teacher();
$teacher->talk();
$teacher->play();
?>

运行:

image.png

trait
代码:

<?php
trait MyTrait
{
    public function justTalk()
    {
        $this->speak();
    }
}
class MyClass1
{
    use MyTrait;
    public function speak()
    {
        echo "speak from MyClass1".PHP_EOL;
    }
}
class MyClass2
{
    use MyTrait;
    public function speak()
    {
        echo "speak from MyClass2".PHP_EOL;
    }

}
$MyClass1 = new MyClass1();
$MyClass1->justTalk();
$MyClass2 = new MyClass2();
$MyClass2->justTalk();
?>

运行:

image.png
上一篇 下一篇

猜你喜欢

热点阅读