<?php /** * 抽象类Animal */ abstract class Animal { abstract public function eat($food); abstract public function sleep(); } /** * 接口Ability1 */ interface Ability1 { public function dig(); } /** * 接口Ability2 */ interface Ability2 { public function climb(); } /** * 兔子类(继承Animal抽象类并实现Ability1接口) */ class Rabbit extends Animal implements Ability1 { public function eat($food) { echo "兔子吃{$food}" . PHP_EOL; } public function sleep() { echo '兔子睡觉' . PHP_EOL; } public function dig() { echo '兔子打洞' . PHP_EOL; } } /** * 猴子类(继承Animal抽象类并实现Ability2接口) */ class Monkey extends Animal implements Ability2 { public function eat($food = '香蕉') { echo "猴子吃{$food}" . PHP_EOL; } public function sleep() { echo '猴子睡觉' . PHP_EOL; } public function climb() { echo '猴子爬树' . PHP_EOL; } } $rabbit = new Rabbit(); $rabbit->eat('胡萝卜'); // 兔子吃胡萝卜 $rabbit->sleep(); // 兔子睡觉 $rabbit->dig(); // 兔子打洞 $monkey = new Monkey(); $monkey->eat(); // 猴子吃香蕉 $monkey->sleep(); // 猴子睡觉 $monkey->climb(); // 猴子爬树
<?php /** * 缓存抽象类 */ abstract class CacheAbstract { abstract public function set($key, $value); abstract public function get($key); abstract public function del($key); } /** * Memcached缓存类 */ class MCache extends CacheAbstract { public function set($key, $value) { // TODO: Implement set() method. } public function get($key) { // TODO: Implement get() method. } public function del($key) { // TODO: Implement del() method. } } /** * Redis缓存类 */ class RCache extends CacheAbstract { public function set($key, $value) { // TODO: Implement set() method. } public function get($key) { // TODO: Implement get() method. } public function del($key) { // TODO: Implement del() method. } } /** * File缓存类 */ class FCache extends CacheAbstract { public function set($key, $value) { // TODO: Implement set() method. } public function get($key) { // TODO: Implement get() method. } public function del($key) { // TODO: Implement del() method. } } // 根据配置决定使用哪种缓存 $conf = 'redis'; // 这里假设从配置文件获取了缓存类型 if ($conf === 'memcached') { $class = 'MCache'; // 使用Memcached缓存 } else if ($conf === 'redis') { $class = 'RCache'; // 使用Redis缓存 } else { $class = 'FCache'; // 使用File缓存 } $cache = new $class(); $cache->set('PHP', 'PHP是世界上最好の语言'); $cache->get('PHP'); $cache->del('PHP');
Copyright © 2024 码农人生. All Rights Reserved