Неустранимая ошибка: Uncaught ArgumentCountError: слишком мало аргументов для функции AmazonAPI :: construct (), 0 передано - PullRequest
0 голосов
/ 18 января 2020

Я получаю эту ошибку

Неустранимая ошибка: Uncaught ArgumentCountError: слишком мало аргументов для функции AmazonAPI :: __ construct (), 0 передано в F: \ xampp \ htdocs \ amazon \ index. php в строке 151 и ровно 3 ожидается в F: \ xampp \ htdocs \ amazon \ index. php: 32 Трассировка стека: # 0 F: \ xampp \ htdocs \ amazon \ index. php (151): AmazonAPI- > __ construct () # 1

Как я могу исправить эту проблему, пожалуйста, дайте мне решение

class AmazonAPI {

    public $amazon_aff_id;
    public $amazon_access_key;
    public $amazon_secret_key;

    public $url_params;
    public $itemID;
    public $xml;

    public $operation;
    public $signature;
    public $response_groups = "Small,Images,OfferSummary";

    public $error_message;
    public $error=0;


    public function __construct($affid, $access, $secret)
    {
        $this->amazon_aff_id = 'mybuyerxpo1-20';
        $this->amazon_access_key = 'AKIAJWDJOLXYKUI0000';
        $this->amazon_secret_key = 'XivGPw/aQfMGXcgi/BqR2F36hO/h1y3rjjfjoook';
    }

    public function build_url()
    {
        $url = "http://webservices.amazon.com/onca/xml?";

        $this->response_groups = str_replace(",", "%2C", $this->response_groups);

        $url_params = "AWSAccessKeyId=" . $this->amazon_access_key;
        $url_params .= "&AssociateTag=" . $this->amazon_aff_id;

        if(!empty($this->itemID)) {
            $url_params .= "&ItemId=" . $this->itemID;
        }

        $url_params .= "&Operation=" . $this->operation;
        $url_params .= "&ResponseGroup=" . $this->response_groups;
        $url_params .= "&Service=AWSECommerceService";
        $url_params .= "&Timestamp=" . rawurlencode(gmdate("2019-10-01\ 16:26:45 UTC\Z"));
        $url_params .= "&Version=2019-10-01";

        $this->url_params = $url_params;

        $url .= $url_params;
        $url .= "&Signature=" . $this->generate_signature();

        return $url;
    }

    public function generate_signature()
    {
        $this->signature = base64_encode(hash_hmac("sha256",
            "GET\nwebservices.amazon.com\n/onca/xml\n" . $this->url_params,
            $this->amazon_secret_key, True));
        $this->signature = str_replace("+", "%2B", $this->signature);
        $this->signature = str_replace("=", "%3D", $this->signature);
        return $this->signature;
    }

    public function item_lookup($id)
    {
        $this->operation = "B07KW8SL6Z";
        $this->itemID = $id;

        $url = $this->build_url();

        $ch = curl_init();  

        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

        $output = curl_exec($ch);

        curl_close($ch);

        $this->xml = simplexml_load_string($output);
        return $this;
    }

    public function check_for_errors()
    {
        if(isset($this->xml->Error)) {
            $this->error_message = $this->xml->Error->Message;
            $this->error = 1;
        }
        if(isset($this->xml->Items->Request->Errors)) {
            $this->error_message = $this->xml->Items->Request->Errors->Error->Message;
            $this->error = 1;
        }
        return $this->error;
    }

    public function get_item_price($product)
    {
        $price = 0;
        if(isset($product->LowestNewPrice)) {
            $price = $product->LowestNewPrice->Amount;
        } elseif(isset($product->LowestUsedPrice)) {
            $price = $product->LowestUsedPrice->Amount;
        } elseif(isset($product->LowestCollectiblePrice)) {
            $price = $product->LowestCollectiblePrice->Amount;
        } elseif(isset($product->LowestRefurbishedPrice)) {
            $price = $product->LowestRefurbishedPrice->Amount;
        }
        return $price;
    }

    public function get_item_data()
    {
        if($this->check_for_errors()) return null;

        $product = $this->xml->Items->Item;
        $item = new STDclass;
        $item->detailedPageURL = $product->DetailPageURL;
        $item->link = "https://www.amazon.com/gp/product/".$this->itemID."/?tag=" . $this->amazon_aff_id;
        $item->title = $product->ItemAttributes->Title;
        $item->smallImage = $product->SmallImage->URL;
        $item->mediumImage = $product->MediumImage->URL;
        $item->largeImage = $product->LargeImage->URL;

        $item->price = $this->get_item_price($product->OfferSummary);

        return $item;
    }

}

Ответы [ 2 ]

1 голос
/ 18 января 2020

public function __construct($affid, $access, $secret): вашему конструктору требуются 3 параметра: $affid, $access и $secret, но вы их не используете.

Замените конструктор на __construct() без каких-либо параметров.

0 голосов
/ 18 января 2020

Вместо того, чтобы жестко кодировать важные детали в вашем классе, вы присваиваете значения по умолчанию параметрам и затем предоставляете значения для этих параметров во время выполнения.

Эта же идея может использоваться для других методов, которые имеют параметр, например, item_lookup в настоящее время имеет атрибут $id, но выглядит так, как будто вы можете назначить другой параметр для $operation (если это никогда не изменится)

public function __construct( $affid=false, $access=false, $secret=false ){
    if( $affid && $access && $secret ){
        $this->amazon_aff_id = $affid;
        $this->amazon_access_key = $access;
        $this->amazon_secret_key = $secret;
    } else {
        trigger_error('Affid, Access and Secret are required');
    }
}

Так, когда класс вызывается, вы будет делать что-то вроде:

error_reporting( E_ALL );

$affid = 'mybuyerxpo1-20';
$access = 'AKIAJWDJOLXYKUIB537A';
$secret = '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';

$app=new AmazonAPI( $affid, $access, $secret );
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...