gpt4 book ai didi

php - php中多重继承的最佳方式是什么?

转载 作者:行者123 更新时间:2023-12-05 00:06:26 25 4
gpt4 key购买 nike

我有主类,应该扩展 3 个特定类。

主要要求是:

-For OOP I need to demonstrate code structuring in meaningful classes that extend each other, so would be an abstract class for the main product logic. An approach for this would be to have a product base class, that would hold all logic common to all products and then specific product type would extend the product base class with that type-specific stuff.

-The idea is to create an abstract class with all product common logic, like getTitle, setTitle etc. Then create child product classes for each product type to store product type specific logic like furniture sizes, CD size, book weight etc..



这个任务我用 解决了php 特征 :

主.php
class Main 
{
use Book;
use Disc;
use Furniture;
// common properties and methods
}

光盘.php
trait Disc
{
public function setSize($size)
{
$this->size = $size;
}
}

Book.php
trait Book
{
public function setWeight($weight)
{
$this->weight = $weight;
}
}

家具.php
trait Furniture
{
public function setHeight($height)
{
$this->height = $height;
}
public function setWidth($width)
{
$this->width = $width;
}
public function setLength($length)
{
$this->length = $length;
}
}

我已经用这样的接口(interface)解决了这个问题:

主.php
class Main
{
// common properties
}

类型.php
interface Weight
{
public function setWeight($weight);
}
interface Size
{
public function setSize($size);
}
interface Fdim extends Weight,Size
{
public function setHeight($height);
public function setWidth($width);
public function setLength($length);
}
class Furniture extends Main implements fdim
{
public function setWeight($weight)
{
$this->weight = $weight;
}
public function setSize($size)
{
$this->size = $size;
}
public function setHeight($height)
{
$this->height = $height;
}
public function setWidth($width)
{
$this->width = $width;
}
public function setLength($length)
{
$this->length = $length;
}
}

这是具有响应上述要求的接口(interface)的最佳解决方案吗?

哪个是更可接受的特征或接口(interface)?你有什么建议吗?

我有一个问题:对于上述要求的任务,是否有更好的解决方案?我也尝试过抽象类和接口(interface),但在我看来,需求对特征更满意。你有什么建议吗?

最佳答案

正如我在评论中所写,我会建议这样的事情:

abstract class Product
{
// Get/Set title, SKU, properties which are common for *all* products
}

然后是一些接口(interface):

interface HavingWeight
{
// Get/Set weight
}

性状:

trait WithWeigth
{
// Get/Set weight implementation
}

然后是 Book的具体类:

class Book extends Product implements HavingWeight
{
use WithWeight;
}

使用接口(interface)有一个非常重要的优势,即使用可以使用如下代码:

if($product instanceof HavingWeight)
{
// Show weight
}

关于php - php中多重继承的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58363261/

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