开发者

Calling php function with exact variables [closed]

开发者 https://www.devze.com 2023-04-06 12:30 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

Lets say we have function that gets 5 variables.

function func($var1, $var2, $var3, $var4, $var5 ) 
{
  if ($var1==1)
  {
    work with $var2, $var3
  }
  if ($var1==2)
  {
    work with $var4, $var5
  }
}

For example, we want to call this function like that: func(1,$var2, $var3) (with开发者_如何转开发out unused variables) or like that func(2,$var4, $var5).

Is it possible? How to send exact variables to php function?

UPDATE Based on @marcus's answer I modified my function.

<?

function GenerateTopNav($current, $lang, $db)
{
    $result=$db->query("SELECT `id`, `parent`, $lang FROM `nav` WHERE `menu`='1'");
        while ($row=$result->fetch_object()){
            echo '<a ';
            if($row->id==$current)
            echo 'class="active"';
            echo 'href="index.php?id='.$row->id.'">'.$row->$lang.'</a> | ';
    }

function GenerateLeftNav($parent, $level, $lang, $db){  
         $q = $db->query("SELECT `id`, `$lang` AS name FROM nav WHERE parent = '$parent' AND `menu`='2'");
          if($level > 0 && $q->num_rows > 0){
          echo "\n<ul>\n";
          }
          while($row=$q->fetch_object()){
                echo "<li>";
                echo '<a href="?page=' . $row->id . '">' . $row->name . '</a>';
                //display this level's children
                GenerateLeftNav($row->id, $level+1, $lang, $db);
                echo "</li>\n\n";
            }
          if($level > 0 &&  $q->num_rows > 0){
                echo "</ul>\n";
            }
          }
}
?>


You should not try to pack these things into one function. Every function should have one purpose and one purpose only. If the two tasks are very very similar, you may do it but this is not given here.

What you can and should do is breaking down your code into smaller functions which take over the similar bits. For example you could have a function called createLinkMarkup() which would return the HTML markup for one link element. This function you could then call from both 'mother' - functions.

But far more important are a few things you're doing wrong:

Variable and function naming

  • don't call functions 'func', it's the worst thing you can do, nobody will know what that functions does
  • use 'verbs' for function names, so don't call them menu either, much better: createMenuMarkup()
  • don't ever use numbers in function names, it makes the code unreadable as well. Your second function could be called createSubmenuMarkup(). Such names are readable. Good for you in a couple of weeks when you have to read your code again and good for any other coder who sees your code... like us.
  • In the same way, don't call variables $var. That's the worst thing you can do for readability (and readability = code quality). Use names that describe containers, use nouns which describe exactly what it is you're passing around. And what @animuson says is not true, you need to name your variables properly. Yes, your code will work with fuzzy names, but it won't be readable=maintainable=worthy-to-survive.

Usage of globals

  • Do not make the db connection a global variable, in fact, do not use globals, that's a very good rule of thumb. What if you need to rename your variable, will you want to rename it in 100 different places in your code? Globals go against the best practice of encapsulation. Better ways: Pass the connection into the function, make the connection available to the class and inject it into this class, or similar to globals but much easier to manage, store the connection in a registry (registry pattern).

Echo from within functions

  • Do not use echo within functions. Instead, store every bit of markup in a string and then return the markup. This way you can always control, what you finally render because you can manipulate it after the function has run already.

SQL injection

  • Beware of SQL injection. You're passing the parameter $lang into your query, where does it come from, maybe from the querystring? If it can be manipulated by users, you're in danger. Use prepared statements or at least mysql_real_escape_string to prevent this.


Why do you even need to specify 4 variables? You're basically saying specify a type and then 2 input variables for that type, so if there will always be 3 variables, just do the follow:

function ($type, $var1, $var2) {
    if ($type === 1) {
        // $var1 = lang and $var2 = current
        // do something with var1 and var2
    } else {
        // $var1 = parent and $var2 = level
        // do something else with var1 and var2
    }
}

You really don't need to spam your function with an excess number of variables that won't get used.

To be more clear: the variables don't need to be named appropriately, you just need to comment that if type = 1, these two variables mean these two things, and if type = 2, these two variables mean these two things and process both types accordingly.


for optional arguments, you can put a default value for them:

func($val1,$val2,$val3 = 0,$val4 = 0)

and you needn't to call them.

func($val1,$val2)


You can use an array:

function func($var1, $array ) 
{
  if ($var1==1)
  {
    work with $array["var2"], $array["var3"]
  }
  if ($var1==2)
  {
    work with $array["var4"], $array["var5"]
  }
}

and call it like this:

func(1, array(
  "var2" => "foo",
  "var3" => "bar"
));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号