Yanick Lafontaine Yanick Lafontaine - 2 months ago 21
PHP Question

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?

Answer

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.

Comments