开发者

PHP: how to return the right stuff

In my function I have more variables:

        $disallowGallery = 1;
        $disallowFriend = 1;
        $disallowWall = 1;开发者_JAVA技巧
        $disallowPM = 1;
        $disallowStatusComment = 1;

Now, i have a $check parameter. If it contains 'Gallery' the function should return the $disallowGallery variable. If it contains 'Friend' it should return the $disallowFriend variable.

I can do this myself with alot of if else statement / or an switch. But does there exist a more effective/simpler way?


The cleanest way to store this in my eyes would be an array:

$disallow = array(
    "Gallery" => 1,
    "Friend" => 1,
    "Wall" => 1,
    "PM" => 1,
    "Comment" => 1
);

Inside a check function, you would do a check like so:

function check("Comment")
....
if (array_key_exists($area, $disallow))
 return $disallow[$area];
else 
 return 0; 


You can use variable variables:

function isDisallowed($type) {
    $disallowGallery = 1;
    $disallowFriend = 1;
    $disallowWall = 1;
    $disallowPM = 1;
    $disallowStatusComment = 1;

    $type = "disallowed$type";
    return isset($$type) ? $$type : 1;
}

But I'd be more tempted to store your configuration in an associative array:

function isDisallowed($type) {
    $disallowed = array (
        'Gallery' => 1,
        'Friend'  => 1,
        // ...
        'StatusComment' => 1,
    );

    return array_key_exists($type, $disallowed) ? $disallowed[$type] : 1;
}


return ${'disallow' . $check};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜