Question

I have a function in php:

function renden(array $additional_css_files = array(), $load_js = true, $load_keen = false, $allow_robots = false, $generate_csrf = true) {

}

It is becoming really nasty to specific all the optional parameters each time. I'd like to do the following trick using or'd flags (bitmask) as a single function parameter.

define("LOAD_JS", 1);
define("NO_LOAD_JS", 0);
define("LOAD_KEEN", 1);
define("NO_LOAD_KEEN", 0);
define("ALLOW_ROBOTS", 1);
define("NO_ALLOW_ROBOTS, 0);
define("GENERATE_CSRF", 1);
define("NO_GENERATE_CSRF", 0);


function render(array("foo"), LOAD_JS | NO_LOAD_KEEN | NO_ALLOW_ROBOTS | GENERATE_CSRF) {

}

See (http://www.php.net/manual/en/function.json-encode.php) and the paramter options. How do I code this logic inside the function?

Was it helpful?

Solution

Change your define's to bitmasks:

// using binary literal notation requires PHP 5.4
define("LOAD_JS", 0b00000001);
define("LOAD_KEEN", 0b00000010);
define("ALLOW_ROBOTS", 0b00000100);
define("GENERATE_CSRF", 0b00001000);

Call your function as follows:

$flags = LOAD_JS | LOAD_KEEN | ALLOW_ROBOTS | GENERATE_CSRF;
render(array("foo"), $flags);

Inside your functions, extract the flags as follows:

function renden(array $additional_css_files = array(), $flags = 0b00001001);
$load_js = $flags & LOAD_JS;
$load_keen = $flags & LOADKEEN;
// ...etc
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top