【问题标题】:PHP catching excepion from another class in a loopPHP在循环中从另一个类中捕获异常
【发布时间】:2018-10-30 12:34:34
【问题描述】:

我是 PHP 新手,在创建以下应用程序的同时学习。我被困在试图捕捉打破Basic类循环的异常。异常来自 ProductVariation 类。函数 generateRandomItems 应该在 Product 类和 product.json 文件的基础上生成随机项目,当 color 为空时跳过 productVariation。

<?php

class Product implements Item
{
    public $id;
    public $name;
    public $price;
    public $quantity;

    public function __construct($file)
    {
        if (!file_exists($file)) {
            throw new Exception('ProductFileNotFound');
        }
        $data = file_get_contents($file);
        $product = json_decode($data);

        $id = $product->id;
        $name = $product->name;
        $price = $product->price;
        $quantity = $product->quantity;

        $this->id = $id;
        $this->name = $name;
        $this->price = $price;
        $this->quantity = $quantity;

    }
    public function getAmount()
    {
        $this->amount = $this->price * $this->quantity;
        return $this->amount;
    }
    public function __toString()
    {
        $output = '';
        foreach ($this as $key => $val) {
            $output .= $key . ': ' . $val . "<br>";
        }
        return $output;
    }
    public function getId()
    {
        return $this->id;
    }
    public function getNet($vat = 0.23)
    {
        return round($this->price / (1 + $vat), 2);
    }
}

class ProductVariation extends Product
{
    public $color;
    public function __construct($file, $color)
    {
        parent::__construct($file);
        $this->color = $color;
        if (!is_string($color)) {
            throw new Exception('UndefinedVariantColor');
        }
        return $this->color;
    }
}

interface Item
{
    public function getId();
    public function getNet($vat);
}

class Products extends ArrayIterator
{
    public function __construct($file, $color)
    {
        $this->product = new Product($file);
        $this->productVariation = new ProductVariation($file, $color);
    }
}

class Basic
{
    public function generateRandomString($randomLength)
    {
        $characters = 'abcdefghijklmnopqrstuvwxyz';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $randomLength; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }
    public function generateRandomItems($length)
    {
        $colors = array(
            "red", "green", "blue",
            "white", "black", null,
        );
        $list = [];
        for ($i = 2; $i < $length + 2; $i += 2) {
            $color = $colors[array_rand($colors, 1)];
            $products = new Products('product.json', $color);
            $products->product->id = $i - 1;
            $products->product->name = $this->generateRandomString(rand(3, 15));
            $products->product->price = rand(99, 10000) / 100;
            $products->product->quantity = rand(0, 99);

            $products->productVariation->id = $i;
            $products->productVariation->name = $this->generateRandomString(rand(3, 15));
            $products->productVariation->price = rand(99, 10000) / 100;
            $products->productVariation->quantity = rand(0, 99);

            echo $products->product;
            echo $products->productVariation;

            array_push($list, $products->product, $products->productVariation);
        }
        $uid = uniqid();
        $fp = fopen("products/" . $uid . '.json', 'w');
        fwrite($fp, json_encode($list));
        fclose($fp);
    }
}

product.json 文件内容为 {"id":1,"name":"Produkt testowy","price":13.99,"quantity":19}

【问题讨论】:

  • 异常是否与颜色为空有关?有什么错误?
  • 颜色要求是字符串。致命错误:未捕获的异常:C:\Users\Mateusz\Desktop\zadania\Test\index.php 中的 UndefinedVariantColor:60 堆栈跟踪:#0 C:\Users\Mateusz\Desktop\zadania\Test\index.php(78) : ProductVariation->__construct('product.json', NULL) #1 C:\Users\Mateusz\Desktop\zadania\Test\index.php(103): Products->__construct('product.json', NULL) # 2 C:\Users\Mateusz\Desktop\zadania\Test\index.php(141): Basic->generateRandomItems(10) #3 {main} 抛出

标签: php class exception try-catch


【解决方案1】:

首先,检查应该在分配之前检查它是否为空(这是在您的 Basic 类中)。

  // put check first 
    if (!is_string($color)) {
        throw new Exception('UndefinedVariantColor');
    }
       $this->color = $color;

【讨论】:

    猜你喜欢
    • 2013-08-13
    • 2017-04-07
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多