how to use constant from class as an argument definition in php function?

前端 未结 2 442
遇见更好的自我
遇见更好的自我 2021-02-06 03:26

I have a class:

class FetchMode 
{
 const FetchAll = 0;
 const FetchOne = 1;
 const FetchRow = 2;}

and a function:

function get         


        
相关标签:
2条回答
  • 2021-02-06 04:17

    You've hinted PHP to expect an instance of FetchMode (just like it says in the error message), but FetchMode::FETCH* passes the constant value. You'd have to use some sort of Enum instance (which we dont have natively in PHP. (Oh well, there is SplEnum but who uses that?)) or change the method signature to exclude the typehint.

    However, instead of a Switch/Case you could solve this more easily via Polymorphism and a Strategy pattern, e.g. instead of doing something like

    public function getRecordSet($mode)
    {
        switch ($mode) {
            case FetchMode::ALL:
                // code to do a fetchAll
                break;
            case FetchMode::ONE:
                // code to do a fetchOne
                break;
            default:
        }
    }
    

    which will increase the Cylcomatic Complexity of your class and forces changes to that class and FetchMode whenever you need to add additional FetchModes, you can do:

    public function getRecordSet(FetchMode $fetchModeStrategy)
    {
        return $fetchModeStrategy->fetch();
    }
    

    and then have an interface to protect the variation

    interface FetchMode
    {
        public function fetch();
    }
    

    and add concrete FetchMode classes for each supported FetchMode

    class FetchOne implements FetchMode
    {
        public function fetch()
        {
            // code to fetchOne
        }
    }
    class FetchAll …
    class FetchRow …
    

    This way, you'll never have to touch the class with that getRecordSet method again because it will work for any class implementing that FetchMode inteface. So whenever you have new FetchModes, you simply add a new class, which is much more maintainable in the long run.

    0 讨论(0)
  • 2021-02-06 04:18

    I don't know what you mean by

    would like to offer a list of possible choices in calling a function. Is it possible in php?

    but for the error part: Imagine you have a var, e.g. $foo. When you do echo $foo you don't get the name of the var but its value. This is because a var has a name and points to a value. Every access to the var basically returns the value it points to. Its the same with constants; You put the constant name in there, but basically you are pointing to your stored value. Which means getRecordSet(FetchMode::FetchOne); and getRecordSet(1); is the same.

    So, getRecordSet(FetchMode $FetchMode) raises must be an instance of FetchMode because FetchMode::FetchOne points to an integer.

    To fix this, you need to use getRecordSet(int $FetchMode).

    0 讨论(0)
提交回复
热议问题