donmqryh49993 2013-12-21 20:46
浏览 66
已采纳

PHP在它自己的构造函数中创建对象

EDIT: Link to my first question. Might clear some things up. PHP Get corresponding data, with default and error handling

I have a function that checks if a GET statement exists. If so, it passes the value to a other function that then selects a class based on the value of the GET statement.

explaining: The url = Page=Contact
The GetFormVariable approves it, and the class Contact is selected and it will give back a string. This string is used as an object 'Content' that, as it says, creats the content of the page.

public function getFormVariable($value){

    switch (strtoupper($_SERVER['REQUEST_METHOD'])) {
        case 'GET':
            if (isset($_GET[$value]) && $_GET[$value] != NULL) {
                return $_GET[$value];
            }
            else{
                return false;
            }
            break;
            case 'POST':
                if (isset($POST[$value]) && $POST[$value] != NULL) {
                return $POST[$value];
            }
            else{
                    return false;
            }
                break;

        default:
            return false;

    }
}

Now the question. When there is no GET statement in the url. The GetFormVariable returns false. And this means there is nothing shown.

How do i give this constructor.

public function SetProperty ($prob, $val){
    $this->$prob = $val;
}

The information to create the ContentHome.
SetProperty('Content', 'ContentHome');

Sorry for poor explanation, if anything is unclear please tell me so.

  • 写回答

2条回答 默认 最新

  • ds11111111111111111 2013-12-21 20:59
    关注

    I'm suggesting we close this question as unclear what you're asking, but decided to throw some help on the provided code sample anyway...

    You can strip this down dramatically, and since there's no context, the function can be static too.

    static public function getFormVariable($value)
    {
        if($_SERVER['REQUEST_METHOD'] == 'GET' &&
           isset($_GET[$value])                &&
           !empty($_GET[$value]))
            return $_GET[$value];
    
        elseif($_SERVER['REQUEST_METHOD'] == 'POST' &&
               isset($POST[$value])                 &&
               !empty($POST[$value]))
            return $POST[$value];
    
        return false;
    }
    

    Your original isset and != NULL checks were doing the same check. Maybe you want the empty() check as a third check, but look it up to be certain.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?