Reputation: 462
How can I define a PHP function with a parameter accepting a fixed set of values similar to filter_var
which accepts as argument various values as in caps:
http://php.net/manual/en/filter.filters.validate.php
I am guessing it will be something like:
function f(int $params) { ... }
but the question is how to make my own fixed caps typed associations?
Example to clarify:
Currently I have 2 functions:
function defineDirConstant($constant, $dirname) {
if (is_dir($dirname) && is_readable($dirname)) {
define(__NAMESPACE__ . '\\' . $constant, $dirname . DIRECTORY_SEPARATOR);
} else {
// some other logic
}
}
function defineFileConstant($constant, $filename) {
if (is_file($filename) && is_readable($filename)) {
define(__NAMESPACE__ . '\\' . $constant, $filename);
} else {
// some other logic
}
}
which I am willing to combine into one:
function defineFilesystemConstant($constant, $filename, int $type) {
// some logic considering the $type
}
I know in this particular case I can use a Boolean for type but my question is in general: how to make a humanly readable parameter which is able to be typed as text. E.g. the function call would be
f("ONE", "foo.txt", TYPE_FILE);
f("BAR", "bar", TYPE_DIR);
f("JIM", "jimcarrey", TYPE_SOMETHING_ELSE);
I hope that clarifies.
Upvotes: -1
Views: 705
Reputation: 90776
I think what you are looking for is the define() function - you can use that to create constants like those used by the filter_var
function.
In your example, you would create these constants:
define('TYPE_FILE', 1);
define('TYPE_DIR', 2);
define('TYPE_SOMETHING_ELSE', 3);
which you can then use in, for example, f("BAR", "bar", TYPE_DIR);
.
Or if you want to avoid global constants, you can scope them using a class:
class FileSystemType {
const FILE = 1;
const DIR = 2;
const SOMETHING_ELSE = 3;
}
Which you can then access using:
f("BAR", "bar", FileSytemType::DIR);
Upvotes: 1
Reputation: 3795
Look here http://php.net/manual/en/migration56.new-features.php:
function f($req, $opt = null, int ...$params) {
printf('$req: %s; $opt: %s; number of params: %s'."\n",
$req, $opt, count($params));
}
This function take $reg
and $opt
as parameters and the array $params
hold all next parameters and convert it to int
So f(1,2,3,4)
has $reg=1 $opt=2, $params=[3,4]
.
Or f(1,2,3,4,'5')
has $reg=1 $opt=2, $params=[3,4,5]
.
Know you can check $params
and only use valid parameters [ENUMS].
To define ENUMS you can do:
interface MyEnums {
const VALUE1 = 1;
const VALUE2 = 2;
}
echo MyEnums::VALUE1;
So if you combine these 2 technics you have something simlliar to your example.
f(1,2,MyEnums::VALUE1,MyEnums::VALUE2);
Keep the comment from @this.lau_ above in mind.
Upvotes: 1