You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
<?php /** * 还不能掌握什么是协变 * 创建了一个animal的抽象类,留了speak叫这个动作给子类具体化 * 创建一个dog类,继承了animal类,并且具体化了叫这个类,狗会吠,猫会喵 */
abstract class Animal{ protected string $name; public function __construct(string $name){ $this->name=$name; } abstract public function speak(); }
class Dog extends Animal{ public function speak(){ echo $this -> name." barks".PHP_EOL; } }
class Cat extends Animal{ public function speak(){ echo $this->name." meows".PHP_EOL; } }
$doggy=new Dog("旺财"); $doggy->speak();
interface AnimalShelter{ public function adopt(string $name):Animal; }
class CatShelter implements AnimalShelter{ public function adopt(string $name):Cat{ return new Cat($name); } }
class DogShelter implements AnimalShelter{ public function adopt(string $name):Dog{ return new Dog($name); } }
$kitty=(new CatShelter)->adopt("ricky"); $kitty->speak();
$doggy=(new DogShelter)->adopt("lucky"); $doggy->speak();
class Food{}
class AnimalFood extends Food{}
abstract class Animal{ protected string $name;
public function __construct(string $name){ $this->name=$name; }
public function eat(AnimalFood $food){ echo $this->name."eats".get_class($food); } }
class Dog extends Animal{ public function eat(Food $food){ echo $this->name."eats".get_class($food); } }
$kitty=(new CatShelter)->adopt("ricky"); $catFood=new AnimalFood(); $kitty->eat($catFood).PHP_EOL;
$doggy=(new DogShelter)->adopt("lucky"); $banana=new Food(); $doggy->eat($banana);
?>
|