2010-04-09 30 views
1

我基本上有一個刮對象。我希望能夠POST變量添加到它像PHP:如何動態添加到http_build_query?

$obj->addvar('Name', 'Value'); 

我現在是這樣的:

function addvar($var, $val) { 
    $postvars[] = Array($var=>$val); 
    } 
    function initiate() { 
    $this->q = $postvars; 
    } 
    if(!empty($this->post)) { 
    $this->params = http_build_query($q); 
    } 

我沒有測試過,因爲它太不完整,但希望我的addvar()函數工作?我究竟如何在數組中添加一個鍵+值,以便http_build_query接受它?

IE(這就是我想要的):

$obj->addvar('username', 'abc'); 
$obj->addvar('password', 'foobar'); 
$obj->send(); //.. 

回答

2

你在你的代碼的幾個問題:

  • 在你addvar方法,你不訪問任何實例變量。你正將這些線索分配給一個局部變量。
  • 您的initiate方法無法訪問變量$postvar
  • if子句中,您正在訪問本地變量$q而不是實例變量$this->q
  • 你想傳遞一個數組數組到http_build_query,但必須是一個「正常」數組。

你在混淆了很多!你的類

一個更完整的示例將是有益的,但我認爲它應該看起來更像是這樣的:

class QueryBuilder { 
    private $params = array(); 

    public function addParameter($key, $value) { 
     $this->params[$key] = $value; 
    } 

    public function send() { 
     $query = http_build_query($this->params); 
     // whatever else has to be done to send. 
     // for the sake of this example, it just returns the query string: 
     return $query; 
    } 
} 

例子:

$obj = new QueryBuilder(); 
$obj->addParameter('username', 'abc'); 
$obj->addParameter('password', 'foobar'); 
echo $obj->send(); // echos 'username=abc&password=foobar' 

在一般情況下,如果你已經有html_build_query建立的查詢,你可以追加到該字符串:

$query = http_build_query(array('foo' => 'bar', 'faa' => 'baz')); 
$query .= '&key=value'; 
echo $query; // echos 'foo=bar&faa=baz&key=value' 
+0

+1,比我的回答更好的闡述。 – pinaki 2010-04-09 11:32:50

+0

爲我節省了很多,我在PHP上並沒有那麼糟糕,但是課程從來沒有用過它們。但現在在這種情況下看起來很棒,我把事情弄混了。它工作得非常好,謝謝。 – 2010-04-09 11:34:05

+0

@ oni-kun:如果你是OOP的新手,請閱讀下面的介紹:http://php.net/manual/en/language.oop5.php它會給你一些見解;) – 2010-04-09 11:37:11

1

你可以這樣做:

$postvars[$var] = $val; 

顯然,你需要確保你打電話http_build_query()後所有值都在數組中。

另外$postvars看起來像局部變量,所以它只在該方法中可見(並且將在每次調用時重置)。讓它成爲班級的成員可能會更好。

0

你的addvars代碼在這裏有一些問題($ this-> params似乎在函數initiate()之外),但是否則它應該可以正常工作。

class test{ 
    var $postvars; 
    function addvar($var, $val) { 
    $this->postvars[] = Array($var=>$val); 
    } 
    function initiate() { 
    $this->q = $this->postvars; 
    return http_build_query($this->q); 
    } 
} 

    $obj = new test(); 
    $test->addvars('username', 'abc'); 

    $qry = $test->initiate(); 

這應該有效。但未經測試。