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

I have a class:

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

and function:

 function getRecordSet(FetchMode $FetchMode){ some switch cases } 

I would like to use $ FetchMode as the key criteria, but I get the error: Fatal error allowed: the argument passed to getRecordSet () must be an instance of FetchMode, an integer value

so I call the function:

 getRecordSet(FetchMode::FetchOne); 

I would like to offer a list of possible options for calling a function. Is this possible in php?

+6
source share
2 answers

You told PHP to expect an instance of FetchMode (exactly the same as the error message says), but FetchMode::FETCH* passes the constant value. You will need to use some kind of Enum instance (which we don't have in PHP). (Well, there is SplEnum , but who uses this?)) Or change the method signature to exclude typehint.

However, instead of a switch / case, you could solve this problem with polymorphism and a strategy template , for example, 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 force changes to this class and FetchMode whenever you need to add additional FetchModes, you can do:

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

and then interface protect option

 interface FetchMode { public function fetch(); } 

and add specific FetchMode classes for each supported FetchMode

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

That way, you no longer have to touch the class with this getRecordSet method, because it will work for any class that implements this FetchMode inteface. Therefore, whenever you have new FetchModes, you simply add a new class, which in the end is much more convenient to maintain.

+8
source

I do not know what you mean by

I would like to offer a list of possible options for calling a function. Is this possible in php?

but for the error part: imagine you have var, for example. $foo . When you do echo $foo , you will not get the name var, but its value. This is because var has a name and points to a value. Each access to var basically returns the value that it points to. Same thing with constants; You put a constant name there, but basically you point to your saved value. This means getRecordSet(FetchMode::FetchOne); and getRecordSet(1); match.

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

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

0
source

Source: https://habr.com/ru/post/909812/


All Articles