PHP: Как сделать переменную доступной внутри каждой функции класса?

Почему не удается передать переменную $open_config в функции getInfFromTheSource (), selectWhatIsNeeded (). Насколько я понял, для этого нужно передать их в конструктор и обработать тем способом, который в коде ниже.

class Downloader
{
    public $source_link, $source_html, $dom, $xpath, $open_config;
    
    function __construct($source_link, $source_html, $dom, $xpath, $open_config)
    {
        $this->source_link = $source_link; 

        $this->source_html = $source_html;

        $this->dom = $dom;

        $this->xpath = $xpath;
        
        $this->open_config = $open_config;
                
    }

    public function getInfFromTheSource ()
    {
        
        $open_config = json_decode(file_get_contents('config.json', true));

        $source_link = $open_config->InfSource;
        
        $source_html = file_get_contents($source_link);
        
        return($source_html);
        
    }
    
    public function selectWhatIsNeeded ($source_html) 
    {
       $open_config = json_decode(file_get_contents('config.json', true));
        $xpathstring = $open_config->string_for_xpath;

        $dom = new DOMDocument();
    
        $dom->loadHTML($source_html);
    
        $xpath = new DOMXpath($dom);
    
        $archives_names = $xpath->query('$xpathstring');
                
        return($names);
                    
    }

Может, дело в том, как я создаю экземпляр класса и обращаюсь к методам? Подключаю файл с классом с помощью required_once, а затем:

$obj = new Downloader($source_link, $source_html, $dom, $xpath, $open_config);

$obj->selectWhatIsNeeded($obj->getInfFromTheSource());

Пробовал объявить $open_config глобальной, сделал это ровно так, как это делается в процедурном и срабатывает. А тут почему-то так не выходит... Гуру, если есть время, не могли бы вы подсказать наилучший способ?


Ответы (1 шт):

Автор решения: Алексей Шиманский
$config = json_decode(file_get_contents('config.json', true));
new Downloader(......, $config);

А в методах обращаться через $this->open_config

→ Ссылка