作业1:继承多态与接口
<?php
//抽象、继承
abstract class animals
{
abstract public function roar();
public function speak()
{
echo "this is an " . __CLASS__ . "\n";
}
}
class pig extends animals
{
public function roar()
{
echo "the pig is roaring.\n";
}
public function speak()
{
echo "this is a " . __CLASS__ . "\n";
}
}
class dog extends animals
{
public function roar()
{
echo "the dog is roaring.\n";
}
public function speak()
{
echo "this is a " . __CLASS__ . "\n";
}
}
class monkey extends animals
{
public function roar()
{
echo "the monkey is roaring.\n";
}
public function speak()
{
echo "this is a " . __CLASS__ . "\n";
}
}
function roarcheck()
{
$dog = new dog();
$pig = new pig();
$monkey = new monkey();
$dog->roar();
$pig->roar();
$monkey->roar();
}
roarcheck();
//接口
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 "I am talking.\n";
}
public function play()
{
echo "I am playing.\n";
}
}
$teacher = new teacher();
$teacher->talk();
$teacher->play();
运行截图
twthomework.PNG
作业2: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();
运行截图
twthomework.PNG
网友评论