I’m trying to create a class that uses cURL to make requests to the Twitter API. I’ve done some research on object oriented programming in PHP, and I can’t quite figure out how this should work. The following code returns NULL:
<?php
class twitter {
public function curlQuery($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$json = curl_exec($ch);
curl_close($ch);
$array = json_decode($json);
return var_dump($array);
}
}
$object1 = new twitter;
$object1->url = "http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=2";
$object1->curlQuery($object1->url);
?>
Also, I’m a little unsure when to use $this->variable vs $variable in a PHP class. Shouldn’t all variables mentioned in an class be referenced as $this->variable? Why would you ever not want to reference the variable of the current object?
Well, why are you storing the url in the object, then passing that variable as a parameter to a method of that same object? Seems pointless, because then you could do somethign like:
and then in the curlQuery method:
As for
$this->variablev.s.$variablein PHP,$this->variablemakes that variable a member of the object. It’ll be available to all the methods in the object.$variableby itself will simply be a local variable within a single method. When that method returns, the local variable is destroyed and is no longer available to other methods.In short, use
$this->variablefor things you need persisted within the object and across multiple method calls. Use$variablefor temporary storage within a single method.