我有4个课程响应:
1st - 从url获取JSON字符串输入,将其解码为数组并创建2 variables: $user_id, $user_text (like here below):
class Get_message{
public $user_id, $user_text;
public function get_input(){
$input = json_decode(file_get_contents('myURL'), true);
$user_id = $input['getting value from an array'];
$user_text = $input['getting value from an array'];
//how to return it?
//return $input, $user_id, $user_text? it won't work I guess
}
}
并且有我的第一个问题:如何返回这两个值,以便我可以在另一个类中使用它?
第二 - 检查该字符串是否包含关键字,如果它包含我想要创建另一个JSON的关键字,则 到目前为止,我得到了这个:
class input_recognize{
const KEYWORD_HELP = 'help';
//...some more constants...
const KEYWORD_REPORT = 'report';
public function msg_recognize($user_text)
{
switch ($user_text) {
case self::KEYWORD_HELP:
return new Output_msg(Output_msg::MESS_HELP);
break;
//... some more cases
case self::KEYWORD_REPORT:
return new Output_message(Output_msg::MESS_REPORT);
break;
}
}
}
3rd - 基于上面的类中的情况是真的创建适当的JSON,我的代码看起来像:
class Output_message{
const MESS_REPORT = 1;
const MESS_HELP = 2;
public function __construct($user_id, $user_text){
//I guess I should use $this here, dunno how
$json_output = array(
"first_title" => array(
"id" => $user_id
),
"second_title" => array(
"text" => "text to send"
),
);
$output = json_encode($json_ouput);
}
}
第四 - 我希望能够将$ output输出到该函数并将其发布到url。
我是php,面向对象编程的初学者,我会感激任何帮助和批评。谢谢你的建议。
答案 0 :(得分:0)
public static $userId; self::$userId =
....和cal GetMesage::userId
。 strpos('help', $yourString)
,此处不需要常量。OutputMessage(GetMessage::$userId, GetMessage::$userText);
我不建议你这样做,你只能使用一个类,并将数据从一个方法传递到另一个,你不会真正需要输出或输入,只有2个网址'秒。如果你真的想要4个课程,那么你可以链接它们,一个课程将返回另一个课程。
这只是示范,有一些方法可以实现你想要的,这是一个例子:
class Message{
public static $userId;
public static $userText;
public static $messageType;
public function __construct($inputUrl)
{
$this->getMessage($inputUrl);
$this->parseMessage();
}
private function getMessage($inputUrl){
$input = json_decode(file_get_contents($inputUrl), true);
self::$userId = $input['id'];
self::$userText = $input['text'];
}
private function parseMessage()
{
$messageText = self::$userText;
switch (true) {
case (strpos('help',$messageText) !== false):
self::$messageType = "Help"; //or code, or whatever you want here
break;
//... some more cases
case (strpos('report',$messageText) !== false):
self::$messageType = "Report"; //or code, or whatever you want here
break;
}
}
public function sendResponse($outputUrl){
$jsonOut = array(
"first_title" => array(
"id" => self::$userId
),
"second_title" => array(
"text" => "text to send"
),
);
$output = json_encode($jsonOut);
$ch = curl_init($outputUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $output);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($output))
);
return curl_exec($ch);
}
}
$sendMessage = new Message('inputUrl');
$sendMessage->sendResponse('outputUrl');