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

时间:2016-01-08 22:46:05

标签: php

我在一个班级中有三个功能。

函数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);
    }
}

2 个答案:

答案 0 :(得分:1)

如果函数位于同一个类中,则使用$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() . '.';
    }
}

?>

确保您也在设置属性。

答案 1 :(得分:1)

bltinmodule.c.h

您在<{1}}中实际所做的事情是将$ this-&gt; authors设置为(尚未定义的)$ 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(),而不是将其分配给变量。