Dev*_*dio 5 php oop class multiple-inheritance traits
我有主课程,应该扩展 3 个特定课程。
主要要求是:
-对于 OOP,我需要在相互扩展的有意义的类中演示代码结构,因此将是主要产品逻辑的抽象类。一种方法是拥有一个产品基类,它将保存所有产品通用的所有逻辑,然后特定的产品类型将使用该类型特定的内容扩展产品基类。
-想法是创建一个具有所有产品通用逻辑的抽象类,如 getTitle、setTitle 等。然后为每个产品类型创建子产品类来存储产品类型特定逻辑,如家具尺寸、CD 尺寸、书籍重量等。
我已经用php 特性解决了这个任务:
主要.php
class Main
{
use Book;
use Disc;
use Furniture;
// common properties and methods
}
Run Code Online (Sandbox Code Playgroud)
光盘.php
trait Disc
{
public function setSize($size)
{
$this->size = $size;
}
}
Run Code Online (Sandbox Code Playgroud)
图书.php
trait Book
{
public function setWeight($weight)
{
$this->weight = $weight;
}
}
Run Code Online (Sandbox Code Playgroud)
家具.php
trait Furniture
{
public function setHeight($height)
{
$this->height = $height;
}
public function setWidth($width)
{
$this->width = $width;
}
public function setLength($length)
{
$this->length = $length;
}
}
Run Code Online (Sandbox Code Playgroud)
我已经用这样的接口解决了这个问题:
主要.php
class Main
{
// common properties
}
Run Code Online (Sandbox Code Playgroud)
类型.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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是满足上述要求的接口的最佳解决方案吗?
特性和界面哪个更容易被接受?你有什么建议吗?
我有一个问题:对于上述要求的这项任务是否有更好的解决方案?我也尝试过抽象类和接口,但在我看来,trait 更能满足需求。你有什么建议吗?
正如我在评论中所写的,我会建议这样的事情:
abstract class Product
{
// Get/Set title, SKU, properties which are common for *all* products
}
Run Code Online (Sandbox Code Playgroud)
然后是一些接口:
interface HavingWeight
{
// Get/Set weight
}
Run Code Online (Sandbox Code Playgroud)
特点:
trait WithWeigth
{
// Get/Set weight implementation
}
Run Code Online (Sandbox Code Playgroud)
然后是具体类Book:
class Book extends Product implements HavingWeight
{
use WithWeight;
}
Run Code Online (Sandbox Code Playgroud)
使用接口有一个非常重要的优点,那就是可以使用如下代码:
if($product instanceof HavingWeight)
{
// Show weight
}
Run Code Online (Sandbox Code Playgroud)