简体   繁体   中英

Variable as an argument

I was wondering if i could pass a variable as an argument like in the following example:

function add_sales($checker){
$sales_payload = array(

    'organization_id' => $organization_id,
    'contact_id' => $contact_id,
    'status' => 'Open',
    'subject' => " ".str_replace($strToRemove, "", $_POST['billing_myfield12'])." - ".implode(" ",$checker),
    'start_date' => date("Y-m-d"), // set start date on today
    'expected_closing_date' => date("Y-m-d",strtotime(date("Y-m-d")."+ 14 days")), // set expected closing date 2 weeks from now
    'chance_to_score' => '10%',
    'expected_revenue' => 0, //set the expected revenue
    'note' => $_POST['order_comments'],

    'progress' => array(
    'id'=>'salesprogress:200a53bf6d2bbbfe' //fill a valid salesprogress id to set proper sales progress 
    ),


    "custom_fields" => [["actief_in_duitsland"=>$value]],

);

// add the sales
$sales = $SimplicateApi->makeApiCall('POST','/sales/sales',json_encode($sales_payload));
}

This function has the variable $checker as argument.

I call this variable checker inside the function notice it in the next line:

'subject' => " ".str_replace($strToRemove, "", $_POST['billing_myfield12'])." - ".implode(" ",$checker),

And when i call the function i do it like;

$vertalingen_check = array_intersect($product_names , $vertalingen); 
$vertalingen_count = count($vertalingen_check);

if($vertalingen_count >= 1){
add_sales($vertalingen_check);
}else {}

Will this work? Passing a variable as an arguments like this? I hear you thinking, why dont you go ahead and test it to see for yourself. The problem is i can't test this for some complicated purposes. All i need to know is if something like this is possible

Yes, it's possible.

For what it's worth, to make the answer more than just a "Yes", you're passing it by value by calling the function in that way.

Functionally, it's a good way to handle your use case.

Specifically, it's better than using a global variable.

function add_sales(){
    global $checker;
    $sales_payload = array(

Global variables make your code harder to maintain, because they introduce mechanisms whereby you can affect the value of a variable (and possibly overwrite variables that are in use in other places).

It's also better than passing it by reference.

function add_sales(&$checker){
    $sales_payload = array(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM