更新 按照專家的指導下,我已經修改了代碼是這樣的:OOP風格編碼
<?php
//Class Validation
class transaction_validate{
private $val_id;
function __construct($id) {
$this->val_id = $id;
}
public function status(){
//Call our server and decode json value
$data = $this->get_data($this->val_id);
$obj = json_decode($data);
return $obj->status;
}
public function amount(){
//Call our server and decode json value
$data = $this->get_data($this->val_id);
$obj = json_decode($data);
return $obj->amount;
}
//Create a function for fetching data
private function get_data($sid){
$url = 'https://domain.com/verify/process.php?trx='.$sid;
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
}
$validate = new transaction_validate();
$validate->val_id = '5201211120944';
echo $validate->amount();
echo '<br>';
echo $validate->status();
和輸出是
Warning: Missing argument 1 for transaction_validate::__construct(),
Fatal error: Cannot access private property transaction_validate::$val_id
糊塗了!
============================前一題================ ======================
我剛學OOP風格的PHP代碼。試圖編寫一個個人使用的腳本,這似乎是錯誤的。代碼是:
<?php
//Class Validation
class transaction_validate{
var $val_id;
public function status(){
//Call our server and decore json value
$data = get_data();
$obj = json_decode($data);
return $obj->status;
}
public function amount(){
//Call our server and decore json value
$data = get_data();
$obj = json_decode($data);
return $obj->amount;
}
//Create a function for featching data
private function get_data($val_id){
$url = 'https://domain.com/verify/process.php?trx='.$val_id;
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
}
$validate = new transaction_validate('5201211120944');
echo $validate->amount();
echo '<br>';
echo $validate->status();
和輸出是
Fatal error: Call to undefined function get_data() in /home/userdo/public_html/class.php on line 17
我需要認識到自己做錯了什麼我做到了。
短篇小說被調用(還有更多,你可以在這裏做...):你應該添加一個構造函數($ val_id沒有被設置爲一個對象成員''get_data()'應該是'$ this-> get_data()' –
感謝Matt的回覆。但構造函數的哪個部分?通過cURL獲取數據? – PHPLearner
史蒂夫的答案有它。 :) –