简体   繁体   中英

Cannot Access PHP Object Property

I'm trying to make an xmlhttp request and print out the xml. I created a class with methods and am calling those methods from an object. However, when I attempt to print the output of the method, I get nothing. I'm guessing it's something minor, but I've been trying for awhile now and have made little progress. Thanks in advance for the help.

<?php 
class twitter {

    public $screen_name;
    public $xml;
    public $count;

    public function getUserTimeline($screen_name, $count=5) {
        $request= "https://api.twitter.com/1/statuses/user_timeline.xml?include_entities=true&include_rts=true&screen_name=$screen_name&count=$count";
        return $this->makeRequest($request);
    }

    public function makeRequest($request){
        return $xml = simplexml_load_file($request);

    }

}


$test = new twitter;
$test->screen_name="mattcutts";
$test->getUserTimeline($screen_name=$test->screen_name, $count=5);
print_r($test->xml); //This does not print anything.

?>

You're creating and returning a local variable $xml here in your makeRequest() method:

    return $xml = simplexml_load_file($request);

That should simply be $this->xml :

    $this->xml = simplexml_load_file($request);

You try to access xml variable. But you didn't set it. You can change your method as following.

public function makeRequest($request){
    $this->xml = simplexml_load_file($request);
}

Or you can print $xml as following way.

$xmp = $test->getUserTimeline($screen_name=$test->screen_name, $count=5);
print_r($xml); 

To create twitter object you must use constructor. So instead of $test = new twitter; use $test = new twitter();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM