Как использовать оператор instanceof с абстрактным классом? - PullRequest
0 голосов
/ 17 октября 2019

Как я могу использовать оператор instanceof с этими 3 дочерними классами, расширяющими абстрактный класс?

Когда я создаю все их экземпляры, он выдает результат только с одним продуктом - Книга Конкретные данные. С другими 2 продуктами ( Диск, Мебель ) не отображаются конкретные данные и не добавляются данные в базу данных SQL.

Я хочу использовать этот код с оператором instanceofв index.php (вместо кода вниз), но он работает неправильно.

function show($user) {
    if($user instanceof HavingWeight)
    {
      $user->setWeight($weight);
    } elseif ($user instanceof HavingSize)
    {
      $user->setSize($size);
    } elseif($user instanceof HavingFur_dims)
    {
      $user->setHeight($height);
      $user->setWidth($width);
      $user->setLength($length);
    } else 
    { 
      die("This is not a Product..");
    }
}

show(new Book);
show(new Disc);
show(new Furniture);

index.php

$user = new Book();
$Size = new Disc();
$Fur = new Furniture();

$user->setWeight($weight);    
$Size->setSize($size);    
$Fur->setHeight($height);    
$Fur->setWidth($width);    
$Fur->setLength($length); 

Product.php

abstract class Product
{
  // All common properties and methods
}

Book.php

<?php 

// interfaces
interface HavingWeight
{
    public function setWeight($weight);
}

// traits
trait WithWeight
{
    // setters
    public function setWeight($weight)
    {
        $this->weight = $weight;
    }
}

// Child classes
class Book extends Product implements HavingWeight
{
   use WithWeight;
}

?>

Furniture.php

<?php 
include_once 'classes/Product.php'; 

// interfaces of each product type
interface HavingFur_dims
{
    public function setHeight($height);
    public function setWidth($width);
    public function setLength($length);
}

// traits of each product type
trait WithFur_dims
{
    // setters
    public function setHeight($height)
    {
        return $this->height = $height;
    }

    public function setWidth($width)
    {
        return $this->width = $width;
    }

    public function setLength($length)
    {
        return $this->length = $length;
    }
}

// Child classes
class Furniture extends Product implements HavingFur_dims
{
   use WithFur_dims;
}

?>

Disc.php

<?php 

// interfaces of each product type
interface HavingSize
{
    public function setSize($size);
}

// traits of each product type
trait WithSize
{
    // setters    
    public function setSize($size)
    {
        $this->size = $size;
    }
}

// Child classes
class Disc extends Product implements HavingSize
{
   use WithSize;
}

?>

Как я могу решить эту проблему?

1 Ответ

0 голосов
/ 17 октября 2019

Вы не можете создать экземпляр абстрактного класса, потому что вы получаете фатальную ошибку.

Но вы можете использовать instanceOf abstractClass, чтобы увидеть, расширяет ли производный класс ваш абстрактный класс.

abstract class Product
{
  // All common properties and methods
}

class ProductEx1 extends Product{}


$inst = new ProductEx1;
if($inst instanceOf Product){
  echo "Yes, ProductEx1 is also a instance of Product";
}
...