我正在尝试编写一个API的类,我需要我的构造函数使用一些方法作为参数(因为我会从csv获取数据)..我正在做一些用这个测试:作为构造函数参数的传递方法
class API {
public $a;
public $b;
function __construct(){
$this->a = setA($a);
$this->b = setB($b);
}
function setA($a){
$a = "X";
}
function setB($b){
$b = "Y";
}
}
但它不工作。这甚至可能或正确?
编辑:根据用户Halcyon的要求。
最初的设计是在各种相互作用的功能上进行的。这不是最好的,因为数据一遍又一遍地被读取,而不是从一个地方读取。
为CSV和JSON的方法是:
function getJsonData(){
$stream = fopen('php://input', 'rb');
$json = stream_get_contents($stream);
fclose($stream);
$order_json_data = json_decode($json, true);
return $order_json_data;
}
function getProductsTable($csvFile = '', $delimiter = ','){
if (!file_exists($csvFile) || !is_readable($csvFile))
echo 'File not here';
$header = NULL;
$data = array();
if (($handle = fopen($csvFile, 'r')) !== FALSE){
while (($row = fgetcsv($handle, 100, $delimiter)) !== FALSE){
if (!$header)
$header = $row;
else if($row[0] != ''){
$row = array_merge(array_slice($row,0,2), array_filter(array_slice($row, 2)));
$sku = $row[0];
$data[$sku]['productCode'] = $row[1];
$data[$sku]['Description'] = $row[2];
}
}
fclose($handle);
}
array_change_key_case($data, CASE_LOWER);
return $data;
}
编辑:包括在那里我测试的对象的索引文件。
<?php
require_once 'helpers/API.php';
if (in_array($_GET['action'],array('insertOrder','updateOrder'))){
$api = new API();
file_put_contents('debug/debug_info.txt', "Object response: {$api->a}, {$api->b}", FILE_APPEND | LOCK_EX);
}
'$ a'和'$ b'不存在于构造函数的作用域中;所以相应地定义构造函数定义并在实例化新的API时将它们作为参数传递() –
@MarkBaker当我实例化时,我无法传递它们..这就是问题所在。我正在考虑使用这些方法来获取数据。这是一个坏方法吗? – Onilol
@Onilol数据从哪里来? – Halcyon