更新根据专家的指示,我以这种方式修改了代码:
<?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();
输出是
警告:transaction_validate::__construct() 缺少参数 1,
致命错误:无法访问私有财产 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();
输出是
致命错误:在第 17 行的 /home/userdo/public_html/class.php 中调用未定义函数 get_data()
我需要认识到我做错了什么。