从同一类中的另一个函数中的一个函数访问数组变量


Accessing an Array Variable From One Function in Another Function Within the Same Class

我在一个类中有三个函数。

函数listUpdates()被假定为return $this->authors

如何在同一类中的另一个函数中访问此值?

我正试图在函数get($id)中访问它,但它一直显示为null,然而,当我在listUpdates()中var_dump它时,它看起来没有任何问题。

class AuthorInformation implements ObjectStore
{
    public $authors; 
    function path($arr, $path) {
        preg_match_all("/'['(.*?)'']/", $path, $rgMatches);
        $rgResult = $arr;
        foreach($rgMatches[1] as $sPath)
        {
            $rgResult=$rgResult[$sPath];
        }
        return $rgResult;
    }
    //get the list of author updates
    public function listUpdates($url, $station, $daysOld)
    {
        // get the user params
        $this->url = $url;
        //var_dump("this is the url : " . $url . "<br/>");
        $this->station = $station;
        $this->daysOld = $daysOld;
        curl_init("");
        $wsUrl = $this->url . 'station_id=' . $this->station . '&days_changed=' . $this->daysOld . '&format=json';
        //curl stuff
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL,$wsUrl);
        $result=curl_exec($ch);
        curl_close($ch);
        $author_updates = json_decode($result, true);
        $root = "['response']['userprofiles']";
        $start = $this->path($author_updates, $root);
        //$authors = [];
        $this->authors = [];
        foreach ($start as $author) 
        {
            print $author['user_id'] . "<br>";
            $this->authors[$author['user_id']] = $author;
            // get the sharepoint author by this id
        }
        //var_dump($this->authors);
        return $this->authors;
    }
    //get a single author, based on their user_id
    public function get($id)
    {
        $this->id = $id;
        var_dump("this is the user_id variable passed: ". $id);
        $this->authors = $authors;
        var_dump("<br/> this is the authors from listUpdates: " . $authors);
    }
}
public function get($id)
{
    $this->id = $id;
    var_dump("this is the user_id variable passed: ". $id);
    $this->authors = $authors;
    var_dump("<br/> this is the authors from listUpdates: " . $authors);
}

实际上get()中所做的是将$this->authors设置为(尚未定义)$authors变量。你可能想用取代那条线

$authors = $this->authors;

或者直接使用$this->authors,而不是将其分配给变量。

如果函数在同一类中,则使用$this访问属性和方法。如果是静态函数,则可以使用self::static::

例如:

<?php
class Car 
{
    private $name = 'Ford';
    public function getName()
    {
        return $this->name;
    }
    public function getOutput()
    {
        return 'The car name is ' . $this->getName() . '.';
    }
}
?>

请确保您也在设置属性。