PHP instanceof 和抽象 class

PHP instanceof and abstract class

我有一个像这样的摘要 class :

<?php 
abstract class NoCie {
    const SC = 01;
    const MTL = 02;
    const LAV = 03;
}
?>

我想测试变量 $x 是否仅包含此摘要 class 中的值。

现在我使用 $x instanceof NoCie 但这不起作用可能是因为这个 class 是抽象的并且无法实例化。

这是我要用来验证的代码。

class CustomersTaxes
{

    public $NoCie;
    private $_file;

    public function __construct($file)
    {
        $this->_file = $file;
    }

    public function CheckValidAndWrite()
    {
        $error = false;

        //Numéro de compagnie
        if (!($this->NoCie instanceof NoCie)) {
            $error = true;

        }
    }
}

这是我实例化此 class 的代码:

$t = new CustomersTaxes($_SERVER['DOCUMENT_ROOT'] . '/test.xlsx');
$t->NoCie = NoCie::SC;
$t->NoClient = "d";
$t->CheckValidAndWrite();

我该怎么做?

我认为你混淆了两个概念,但也许你想要的可以通过其他方式实现。我现在唯一能想到的就是使用 PHP 方法类型提示。但我会稍微重构一下,使 NoCie 属性 受保护,只能由 getter 和 setter 操纵。像这样:

class CustomersTaxes
{

    private $NoCie;
    private $_file;

    public function __construct($file)
    {
        $this->_file = $file;
    }

    public function getNoCie()
    {
        return $this->NoCie;
    }

    public function setNoCie(NoCie $NoCie)
    {
        $this->NoCie = $NoCie::VALUE;
    }
}

你仍然需要一个 class 来扩展抽象的,否则它永远不会工作:

class SCA extends NoCie
{

    const VALUE = '01';
}

由于 CustomersTaxes 上的 NoCie 属性 是私有的,因此您必须对其进行一些不同的设置:

$t = new CustomersTaxes($_SERVER['DOCUMENT_ROOT'] . '/test.xlsx');
$t->setNoCie(new SCA());
// ...

这样您就可以确保无论何时设置 NoCie 属性,它都会是您想要的 class。无需验证——如果 setNoCie 由无效值触发,它将抛出异常。

我找到了另一种无需类型提示即可完成这项工作的方法。类型提示似乎是个好方法,但需要很多文件才能与 psr-4 自动加载器一起使用。

我的选择是使用 ReflectionClass 获取所有常量作为数组并比较 $this->SC 的值。

$NoCieReflection = new \ReflectionClass('\Ogasys\Enum\NoCie');
if (!in_array($this->NoCie, $NoCieReflection->getConstants())) {
    $error = true;
    array_push($msg, "# de compagnie invalide");
}