简体   繁体   中英

PHP instanceof and abstract class

I have an abstract class like this :

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

I would like to test if a variable $x contain value from this abstract class only.

For now i used $x instanceof NoCie but this is not working probably because this class is abstract and can't be instantiated.

Here is the code that i'm trying to use to validate.

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;

        }
    }
}

Here is my code that instantiate this class :

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

How can i do that?

I think you are confusing two concepts, but maybe what you want can be achieved in some other way. The only thing I can think of right now is to use PHP method type-hinting. But I would refactor slightly, making the NoCie property protected to be manipulated only by a getter and a setter. Like this:

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;
    }
}

You still need a class that extends the abstract one, though, otherwise it'll never work:

class SCA extends NoCie
{

    const VALUE = '01';
}

Since the NoCie property on CustomersTaxes is private, you have to set it a bit differently:

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

That way you can make sure that whenever a NoCie property is set, it will be the class you want. No need to validate -- if setNoCie is triggered by an invalid value, it'll throw an exception.

I figured out another way to do this job without type hinting. Type hinting seem to be a good way but need to much files to work with psr-4 autoloader.

My choice is to use ReflectionClass to get all constant as array and compare value from $this->SC.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM