Get function arguments values PHP

376

I have a function with 5 arguments and default site width variable

$site_width ='1000px';
function MyPrintFunction ($divName,$width=false,$html1='',$html2='', $echo = true ){
      ... plenty of code above, no need to post complete function

        $html = '<div id="'.$divName.'">';
        $html .= '</div>';
        if( $echo ){
          echo $html1.$html.$html2;
        }else{
          return $html1.$html.$html2;
        }


}

and than I print html like:

MyPrintFunction ('divname1',true);
MyPrintFunction ('divname2');
MyPrintFunction ('divname3');

I need to check if any of these functions has set the second argument to true, and if yes , I need first argument name.

This way I can add the argument name to css snippet ( will be injected in head later ) and set width for it

#ARrument1NameSHouldGoHereAsVariable{
   width:$site_width;
}

I hope I explained this right. Sorry if I did not. Any help is appreciated. Thank you!

731

Answer

Solution:

Noo no no, you absolutely can have optional arguments. It's a bit messy of a situation, but totally possible.

echo MyPrintFunction('dafsd',435);
function MyPrintFunction ($divName,$width=2342){
    return $divName . $width;
}

The reason it is discouraged is because... Let's suppose you want to set a height, but not a width to 435

echo MyPrintFunction('dafsd',435);
function MyPrintFunction ($divName,$width=2222, $height=1111){
    return $divName . $width . $height;
}

Optional arguments should generally not be used, and if they are to place them at the end in an array

Please oh please let this be what you are seeking...

function MyPrintFunction ($divName,$width=false){
    $newObj = array();
    $newObj['divName'] = $divName;
    $newObj['width'] = $width;
    return $newObj;
}
function hasWidth($newObj) {
    if ($newObj['width']) {
        return $newObj['width'];
    }
    else {
        return 'no width!'; 
    }
}
$tempStore1 = MyPrintFunction('dafsd',123);
$tempStore2 = MyPrintFunction('dafsd');
echo hasWidth($tempStore1);
echo hasWidth($tempStore2);
487

Answer

Solution:

What's this for?

function MyPrintFunction ($divName,$width=false,$html1='',$html2='', $echo = true ){

The logic goes like this

<?php
function blahblah($param1, $param2) {
//Put some weirdy stuff here

if($param2 == '1') {
 //Than it's true
  } else {
 //false
  }
}
blahblah("div1", "1"); //This is true
blahblah("div1", "0"); //This is false
?>

People are also looking for solutions to the problem: php - Using extension in Opencart

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.