PHP: How to dynamically add to http_build_query?
I have a scraping object basically. I want to be able to add POST variables to it like
$obj->addvar('Name', 'Value');
What I have now is this:
function addvar($var, $val) {
$postvars[] = Array($var=>$val);
}
function initiate() {
$this->q = $postvars;
}
if(!empty($this->post)) {
$this->params = http_build_query($开发者_StackOverflow社区q);
}
I haven't tested because it's too incomplete, But would my addvar() function work? How on earth do I append a key+value to the array so http_build_query would accept it?
IE (this is what I want):
$obj->addvar('username', 'abc');
$obj->addvar('password', 'foobar');
$obj->send(); //..
You have several issues in your code:
- In your
addvar
method, you are not accessing any instance variables. You are assigning the alues to a local variable. - Your
initiate
method cannot access the variable$postvar
. - In the
if
clause you are accessing a local variable$q
instead of the instance variable$this->q
. - You want to pass an array of arrays to
http_build_query
but is has to be a "normal" array.
You are mixing up a lot!
A more complete example of your class would be helpful, but I think it should look more like this:
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;
}
}
Example:
$obj = new QueryBuilder();
$obj->addParameter('username', 'abc');
$obj->addParameter('password', 'foobar');
echo $obj->send(); // echos 'username=abc&password=foobar'
In general, if you already have the query that was built by html_build_query
you can just append to that string:
$query = http_build_query(array('foo' => 'bar', 'faa' => 'baz'));
$query .= '&key=value';
echo $query; // echos 'foo=bar&faa=baz&key=value'
You can do:
$postvars[$var] = $val;
Obviously you will need to make sure you call http_build_query()
after all of values are in the array.
Also $postvars
looks like a local variable, so it is only visible within that method (and will be reset on every call) . It would probably be better to make it a member of the class.
You have some problems with your addvars code here ($this->params seems outside the function initiate()), but otherwise it should work fine.
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();
This should work. Untested though.
精彩评论