gpt4 book ai didi

php - 带有关键字 Interface , extends , implements 的面向对象的 PHP

转载 作者:可可西里 更新时间:2023-10-31 22:15:47 25 4
gpt4 key购买 nike

在过去的几个月里,我在学习纯 oop 方面取得了长足的进步,现在我正在将设计模式应用到我的工作中!所以我不得不扩展我的 php 知识,我正在使用接口(interface),扩展它们,然后为这些接口(interface)实现类。我的问题是关于从扩展另一个接口(interface)的接口(interface)构造一个类,例如:

interface Car
{
function doGeneralCarStuff();
vinNumber =;
}

interface CompactCar extends Car
{
static $numCompactCars;
function doCompactCarStuff();
}

class HondaCivic implements CompactCar
{
function doGeneralCarStuff()
{
//honk horn , blink blinkers, wipers on, yadda yadda
}

function doCompactCarStuff()
{
//foo and bar and foobar
}

}

class ToyotaCorolla implements CompactCar
{
function doGeneralCarStuff()
{
//honk horn , blink blinkers, wipers on, yadda yadda
}

function doCompactCarStuff()
{
//foo and bar and foobar
}

}


myCar = new HondaCivic();
myFriendCar = new ToyotaCorolla();

好的,现在假设我想了解一些关于我的本田扩展的接口(interface)之一,即 CompactCar 接口(interface)。我想知道已经制造了多少辆紧凑型汽车 ($numCompactCars)。我是深度(对我来说很深:p)OOP 的新手,所以如果我没有正确执行此操作,请提供指导。非常感谢!

最佳答案

工厂模式的唯一缺点是您可以随时绕过它 - 即 new HondaCivic() 会打乱汽车数量。

这里有一些更强大的东西:

<?php

interface Car
{
function doGeneralCarStuff();
}

// Declare as abstract so it can't be instantiated directly
abstract class CompactCar
{
// Increment car count
function __construct() {
CompactCar::$numCompactCars++;
}
function __clone() {
CompactCar::$numCompactCars++;
}
// Decrement car count
function __destruct() {
CompactCar::$numCompactCars--;
}
// Prevent external modification of car count
protected static $numCompactCars;
// Get the current car count
static public function getCount() {
return CompactCar::$numCompactCars;
}
// Require a compact car function for descendant classes
abstract public function doCompactCarStuff();
}

// Extend and implement
class HondaCivic extends CompactCar implements Car
{
function doGeneralCarStuff() { }
function doCompactCarStuff() { }
}

// Extend and implement
class ToyotaCorolla extends CompactCar implements Car
{
function doGeneralCarStuff() { }
function doCompactCarStuff() { }
}

$myCar = new HondaCivic(); // 1 car
$myFriendCar = new ToyotaCorolla(); // 2 cars
printf("Number of compact cars: %d\n", CompactCar::getCount());
$myCar = new HondaCivic(); // still only 2 cars
unset($myFriendCar); // one car left!
printf("Number of compact cars: %d\n", CompactCar::getCount());
$myCar2 = clone $myCar; // now we have two cars again
printf("Number of compact cars: %d\n", CompactCar::getCount());
CompactCar::$numCompactCars = 1000; // sorry, you can't do that!

关于php - 带有关键字 Interface , extends , implements 的面向对象的 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5348526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com