@saniii

Как присвоить глобальную переменную в классе PHP?

Использую класс-обертку cUrl для своих нужд. Так вот проблема в следующем, необходимо использовать прокси , но проблема в том что нужно указывать присвоение прокси в каждой функции где идет запрос через curl можно ли как то сделать что проде глобальной переменной? пример класса ниже под спойлером:
spoiler
<?php

/**
* 
*    Файл-обертка для библиотеки cURL
*
*/

class Curl 
{

	const FOLLOWLOCATION = true;
	const RETURNTRANSFER = true;
	const AUTOREFERER = true;
	const TIMEOUT = 30;
	const CONNECT_TIME = 30;

	public $user_agent = null;
	public $proxy;

	private $ch = null;
	private $url = null;	
	private $httpheaders = [];
	private $postparams = null;
	private $proxy_type = null;
	private $cookies = null;

	
	public function __construct() 
	{
		$this->ch = curl_init();
	}
		
	//	Функция POST/GET - запросов
	public function post($url, $postparams = []) 
	{
		$this->url = $url;	
		if (isset($postparams)) {	
			$this->postparams = $postparams;
		}		
		return $this->exec();
	}
	
	//	Заголовок запроса (!)
	public function addHttpheaders($headers)
	{
		foreach ($headers as $name => $value) {
			if ($name == 'POST') {
				$this->httpheaders[$name] = $name . ' ' . $value;
			} else {
				$this->httpheaders[$name] = $name . ': ' . $value;
			}
		}
	}

	//	Присваемваем USER-AGENT
	public function setUserAgent($user_agent = null)
	{
		$this->user_agent = $user_agent;
	}

	//	Подключение прокси (HTTPS/SOCKS5)
	public function setProxy($proxy_ip, $proxy_type = '')
	{
		$this->proxy = $proxy_ip;
		$this->proxy_type = $proxy_type;
	}

	//	Временное имя дsя cookie файла
	private function nameCookies($name = null)
	{
		for ($i=0; $i<10; ++$i)
            $name .= chr(rand(97, 122));
        return $name . '.temp';
	}

	//	Создание cookie файла
	public function setFileCookies()
	{
		$this->cookies = $this->nameCookies();
		file_put_contents($this->cookies, "");
	}

	//	Удаление cookie файла
	public function clearCookies()
	{
		unlink($this->cookies);
	}

	private function exec()
	{
		curl_setopt($this->ch, CURLOPT_URL, $this->url);
		curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION , self::FOLLOWLOCATION);
		curl_setopt($this->ch, CURLOPT_AUTOREFERER, self::AUTOREFERER);
		curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, self::RETURNTRANSFER);	
		curl_setopt($this->ch, CURLOPT_HEADER, true);
		
		if ($this->postparams)
			curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->postparams);
		
		if (count($this->httpheaders))
			curl_setopt($this->ch, CURLOPT_HTTPHEADER, $this->httpheaders);

		if ($this->proxy)
			curl_setopt($this->ch, CURLOPT_PROXY, $this->setProxyIp());
			
		if ($this->proxy_type == 'socks5')
			curl_setopt($this->ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);

		curl_setopt($this->ch, CURLOPT_TIMEOUT, self::TIMEOUT);
		curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, self::CONNECT_TIME);
		curl_setopt($this->ch, CURLOPT_COOKIEJAR, $this->cookies);	//	Файл для записи cookies
   		curl_setopt($this->ch, CURLOPT_COOKIEFILE, $this->cookies);	//	Файл для чтения cookies
		$response = curl_exec($this->ch);
		$response = substr($response, curl_getinfo($this->ch, CURLINFO_HEADER_SIZE));
				
		$this->postparams = null;
		
		return $response;
	}
	
	public function __destruct()
	{
		curl_close($this->ch);
	}
}

  • Вопрос задан
  • 595 просмотров
Решения вопроса 1
OKyJIucT
@OKyJIucT
Sunshine reggae
При создании экземпляра класса передавайте прокси в конструктор.
public function __construct($proxy) 
  {
    $this->ch = curl_init();
    $this->proxy = $proxy;
  }

и потом
$curl = new Curl('127.0.0.1');
$data = $curl->post('http://ya.ru');

Но у вас же есть метод setProxy, чем он вам не нравится? Здесь не надо каждый раз задавать прокси для этого экземпляра класса, один раз указали, и дальше будет работать с указанным, сколько бы раз вы не вызывали метод exec.
$curl = new Curl();
$curl->setProxy('127.0.0.1');

$data1 = $curl->post('http://ya.ru');
$data2 = $curl->post('http://vk.com');
$data3 = $curl->post('http://google.com');

по сути на одну строку кода больше. Ну либо я неправильно понял ваш вопрос.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы