我需要这个类返回一个字符串值"error25"如果失败,可能吗?-.PHP



大家好,我在php 中有这个类

<?php
namespace ExternalImporterapplicationlibspextractorparser;
defined('ABSPATH') || exit;
class Product {
    public $link;
    public $domain;
    public $title;
    public $description;
    public $price;
    public $currencyCode;
    public $image;
    public $oldPrice;
    public $manufacturer;
    public $inStock;
    public $availability;
    public $category;
    public $condition;
    public $ratingValue;
    public $reviewCount;
    public $features = array();
    public $images = array();
    public $reviews = array();
    public $paused;
    public $categoryPath = array();
    public $extra = array();
}

然而,当使用null值调用它时,它会给我一个致命的错误。我需要当这个错误发生时,它会返回结果:error25

我在函数中这样调用类

public static function update(Product $newProduct, $product_id)
{
//code
}

在本例中,$newProduct的值为NULL,这就是它在函数中生成错误的原因。

如果我能返回错误字符串error25,我就能处理它。

注意:如果解决方案是调用函数,那么它比编辑类本身要好得多。

我的目标是实现这样的东西,但我不确定你能在PHP 中做到

public static function update(Product $newProduct ?: "error25", $product_id)
{
//code
}

编辑可能的解决方案

public static function update($newProduct, $product_id)
{
if (empty($newProduct)) {
# CALL Product $newProduct how to do it?
}
else {
$newProduct = NULL;
}
}

首先,您的错误不是因为参数$newProduct为null,也不是Product的实例。之所以会发生这种情况,是因为方法定义中有逻辑。你不能那样做。

public static function update(Product $newProduct ?: "error25", $product_id)

这不应该奏效。这是一个语法错误。结果为:PHP Parse error: syntax error, unexpected token "?", expecting ")"。请将您的错误报告设置为最高级别,以便您可以看到这些基本错误。

检查类的null或实例

<?php
declare(strict_types=1);
namespace Marcel;
use Exception;
use stdClass;
class Foo
{
    public static function bar(?stdClass $yadda): void
    {
        if ($yadda === null) {
            throw new Exception('$yadda is not an instance of stdClass', 25);
        }
        // or ...
        if (!$yadda instanceof stdClass) {
            throw new Exception('$yadda is not an instance of stdClass', 25);
        }
        // everything okay at this point
        $yadda->someProperty = 'I am a valid stdClass instance';
    }
}

这里发生了什么?静态方法采用一个参数,该参数可以是stdClassnull的实例。如果$yadda为null,则会引发一个异常,其中包含一条消息和一个代码。

捕获类型错误

使用PHP8,您可以捕获类型错误。这是解决你问题的另一个办法。

<?php
declare(strict_types=1);
namespace Marcel;
use stdClass;
use TypeError;
class Test
{
    public static function foo(stdClass $yadda): void
    {
        // some logic here
    }
}
try {
    Test::foo(null);
} catch (TypeErrror $error) {
    var_dump($error->getMessage());
    // MarcelTest::foo(): Argument #1 ($bar) must be of type stdClass, null given
}

您可以在try/catch块中捕获类型错误。如果$yaddastdClass的实例不同,则会引发类型错误。您可以在catch块中处理此错误。使用此解决方案,您不必将参数声明为null或某个类的实例。您可以只声明特定类的类型提示,并在调用静态方法时捕获类型错误。

最新更新