How to create a function in PHP
I'm trying to create a function called saveorder
. This is my code so far:
<?php
//function foo($arg_1, $arg_2, /* ..., */ $arg_n)
function saveorder($orderid,$txnid,$date,$amount)
{
$a_str = array(
"orderid"=>"175",
"txnid"=>"RC456456456",
"date"=>"54156456465",
"amount"=>"109$"
);
$file = 'order.dat';
$contents = implode("|", $a_str);
$contents .= PHP_EOL . PHP_EOL;
file_put_contents($file, $contents);
}
echo "function will return=".saveorder($orderid);
?>
I think I'm doing it wrong because I never created my own 开发者_C百科function. Still, however, I want to create this function to save the order in the order.dat
file. Can anyone please help me create this function? I'm trying very hard but I'm unable to create it.
You didn't return anything.
Apart from that the function is okay:
function saveorder($orderid,$txnid,$date,$amount){
$a_str = array(
"orderid"=>$orderid,
"txnid"=>$txnid,
"date"=>$date,
"amount"=>$amount
);
$file = 'order.dat';
$contents = implode("|", $a_str);
$contents .= PHP_EOL;
file_put_contents($file, $contents, FILE_APPEND);
return $contents;
}
echo "function will return=".saveorder("175","RC456456456","54156456465","109$");
Actually, you didn't return any value in your function, so it did run correctly.
You need add like following statment at the end of function
<?php
function saveorder($orderid,$txnid,$date,$amount) //function foo($arg_1, $arg_2, /* ..., */ $arg_n) {
$a_str = array( "orderid"=>"175", "txnid"=>"RC456456456", "date"=>"54156456465", "amount"=>"109$" );
$file = 'order.dat';
$contents = implode("|", $a_str);
$contents .= PHP_EOL . PHP_EOL;
res = file_put_contents($file, $contents);
if(res){
return true;
} else {
return false;
}
}
echo "function will return=".saveorder($orderid);
?>
精彩评论