简体   繁体   English

PHP的形式下拉菜单正常工作,但使它成为一个函数

[英]php form drop down menu works normally but not when making it into a function

I'm currently going through a PHP tutorial and created a form drop down menu. 我目前正在阅读PHP教程,并创建了一个表单下拉菜单。 I'm trying to make my code more efficient by moving some of the blocks of code into functions. 我试图通过将一些代码块移到函数中来提高代码效率。

Why does the following code not work when making it a function (example 1) but it does work otherwise (example 2)? 为什么以下代码在使其成为函数时不起作用(示例1),但在其他情况下却起作用(示例2)?

Example 1: 范例1:

<div id="leftnav">
<div class="search">

    <form name="search" method="get" action="search.html" id="search">
        <input type="text" value="keywords" name="keyword" class="s0" /> 
        <br />

        <select name="title" class="s2">

        <?php 

            productSelection(); // This is the function I am referring to

        ?> 


        </select>
        <br />
        <input type="submit" name="search" value="Search Products" class="button marT5" />
        <input type="hidden" name="page" value="search" />
    </form>

The function is defined as followed: 该函数定义如下:

productSelection() {

sort($titles, SORT_STRING); // Sort array of products

foreach ($titles as $deserts) {

    printf("<option value=\"%s\">%s</option>", $deserts, $deserts);

}

Example 2: 范例2:

    <form name="search" method="get" action="search.html" id="search">
        <input type="text" value="keywords" name="keyword" class="s0" /> 
        <br />

        <select name="title" class="s2">

        <?php 

            sort($titles, SORT_STRING); // Sort array of products

            foreach ($titles as $deserts) {

                printf("<option value=\"%s\">%s</option>", $deserts, $deserts);

            } 

        ?> 


        </select>
        <br />
        <input type="submit" name="search" value="Search Products" class="button marT5" />
        <input type="hidden" name="page" value="search" />
    </form>

$titles is not available to your function because it is out of scope . $titles无法使用,因为它超出了范围 Global variables are not available inside of functions unless you pass them as parameters (preferred) or use the global keyword (not recommended). 全局变量在函数内部不可用,除非您将它们作为参数传递(首选)或使用global关键字(不推荐)。

productSelection($titles) {
    sort($titles, SORT_STRING); // Sort array of products
    foreach ($titles as $deserts) {    
        printf("<option value=\"%s\">%s</option>", $deserts, $deserts);
    }
}

And when invoking it: 当调用它时:

<?php 
    productSelection($titles); 
?> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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