I have a class:
class FetchMode
{
const FetchAll = 0;
const FetchOne = 1;
const FetchRow = 2;}
and a function:
function getRecordSet(FetchMode $FetchMode){ some switch cases }
I would like to use $FetchMode as switch case criteria but receiving an error:
Catchable fatal error: Argument passed to getRecordSet() must be an instance of FetchMode, integer given
this is how I call a function:
getRecordSet(FetchMode::FetchOne);
I would like to offer a list of possible choices in calling a function.
Is it possible in php?
You’ve hinted PHP to expect an instance of
FetchMode(just like it says in the error message), butFetchMode::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 isSplEnumbut 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
which will increase the Cylcomatic Complexity of your class and forces changes to that class and
FetchModewhenever you need to add additional FetchModes, you can do:and then have an interface to protect the variation
and add concrete
FetchModeclasses for each supported FetchModeThis way, you’ll never have to touch the class with that
getRecordSetmethod again because it will work for any class implementing thatFetchModeinteface. So whenever you have new FetchModes, you simply add a new class, which is much more maintainable in the long run.