如何使用函数参数PHP

时间:2017-08-31 14:23:10

标签: php function variables scope arguments

我试图了解在嵌套函数中使用函数参数的最佳方法:

以下是我的想法:

这是我首先声明稍后在其他函数中使用它们的一堆函数:

//Habitaciones restantes
        function rleft($from, $to, $room_type_id){
            //Acceso a DB
                require('/some-path/database.php');
            //url parameters
                require ('/some-path/getparam.php');
            //Hotel Room Data
                $customroom = mysqli_query($conn, "SELECT * FROM hotel_room_type WHERE room_type_id = '$room_type_id'");
                $customroomtotal = mysqli_num_rows($customroom);
                $customroomData = mysqli_fetch_array($customroom);
                $roominventory = $customroomData['room_type_inventory'];
            //Obteniendo lista de disponibilidad
                $customavailable = mysqli_query($conn, "SELECT * FROM booking_check_avilability WHERE room_type_id = '1' AND check_in_date = '$from' AND check_out_date = '$to'");
                $customavailabletotal = mysqli_num_rows($customavailable);
                mysqli_close($conn);
                if($customavailabletotal > 0) {
                    while($customavailableData = mysqli_fetch_array($customavailable))  {         
                            $inventariodisponible = $roominventory - $customavailableData['total_room'] -$customavailableData['blocked_inventory'];
                    }
                } mysqli_free_result($customavailable);
                mysqli_close(conn);
            return $inventariodisponible;
        }
    //Creamos el array donde se almacenarán todos los dias entre las 2 fechas del cliente
        function createRange($startDate, $endDate) {
                $tmpDate = new DateTime($startDate);
                $tmpEndDate = new DateTime($endDate);
                $outArray = array();
                do {
                    $outArray[] = $tmpDate->format('Y-m-d');
                } while ($tmpDate->modify('+1 day') < $tmpEndDate);
            return $outArray;
        }
    //creamos un array donde se almacenará la dispo para cada una de las fechas del cliente
        function inout($room_type_id){
         require ('/some-path/getparam.php');   
            $datearray = createRange("$fromdate", "$todate", "$room_type_id");
            $arraycount = count($datearray);
            $leftarray = array();
            foreach ($datearray as $value) {
                $from = $value;
                $to = date('Y-m-d',strtotime($value . "+1 days"));
                $leftarray[] = rleft($from, $to);
            }
            return $leftarray;
        }
    //Room or Rooms?
        function sp(){
        require ('/some-path/getparam.php');
            if (rleft($fromdate, $todate, $room_type_id) == 1) {
                $rq = "room";
            }
            else{
                $rq = "rooms";
        }
        return $rq;
        }
    //Habitaciones restantes
        function availablerooms(){
            //Acceso a DB
            require('/some-path/database.php');
            //url parameters
            require ('/some-path/getparam.php');
          $keyarray = createrange($fromdate, $todate);
          $valuearray = inout();
          $joinarray = array();
          foreach ($keyarray as $i => $key) {
              $joinarray[$key] = $valuearray[$i];
          }
          return $joinarray;
        }

所以这是主要功能:

//Función para checkar si hay disponibilidad para las fechas seleccionadas
    function next($room_type_id){
        //basic include files
            require('/some-path/database.php');
        //url parameters
            require ('/some-path/getparam.php');
        //Checkamos que haya dispo
        $inoutarray = inout("$room_type_id");
        foreach ($inoutarray as $value) {
           if ($value < $rooms) {
               echo "Sorry NO rooms available!"; //no hay habitaciones disponibles
                    echo "</br>";
                        ?>
                        <!-- Escondemos el botón de submit de la habitación -->
                        <style type="text/css">.bromeliabtn{
                        display:none!important;
                        }</style>
                        <!-- Cambiamos el estilo del msj -->
                        <style type="text/css">.bromeliadsbl span{
                        color: #c58e21!important;
                        font-size: 20px!important;
                        line-height: 25px!important;
                        }</style>
                        <?php
                        $cond = true;//asignamos un valor a $cond
                            break; // si match entonces termina el loop
           }else{
            unset($cond);
            $cond = false;//si hay disponibilidad entonces sumar 1 a $cond
           }
        }
        //si las fechas tienen dispo entonces seguimos :)
        if ($cond == false) {//si $cond es 2 entonces podemos seguir
            allowed();
        }

    }
        //Esta función nos permite obtener los precios tanto de temporada como normales de acuerdo a la fecha especificada.
            function allowed($room_type_id){
            //Acceso a la base de datos
                require('/some-path/database.php');
                require ('/some-path/getparam.php');
                  //Creamos la consulta para precios por temporada
            $sql = "SELECT `seasonal_price`"
                . " FROM `hotel_seasonal_price`"
                . " WHERE `room_type_id` = '$room_type_id'"
                . " AND `room_person` =  '$Room1'"
                . " AND `seasonal_price_deleted` =  '0'"
                . " AND '" . $fromdate . "' = seasonal_from"
                //. " AND '" . $currentdate . "' = 'seasonal_to'"
                . " LIMIT 1";
            $result = mysqli_query($conn, $sql) or die(mysqli_error());
            if (mysqli_num_rows($result) != 0) {
                $seasonalprice = mysqli_query($conn, $sql);
                if (!$seasonalprice) {
                    die('Could not get data: ' . mysqli_error());
                } else {
                    while ($standard2 = mysqli_fetch_assoc($seasonalprice)) {
                        //echo "$ " . $standard2['seasonal_price']  . "";
                        $stdrd = $standard2['seasonal_price'];
                        echo "$ ";
                        echo number_format((float)($stdrd + ((10*$stdrd)/100)), 2, '.', ''); //sumamos el porcentaje de descuento que luego sera restado en el precio principal
                        echo " ";
                        ?>
                        <p style="text-align: center;"><span style="font-family: helvetica; color: #ff0000; font-size: 15px;"><span style="color: #333333;">(Seasonal price)</span></span></p>
                        <?php
                    }
                }
            } 
            else {
            // Hacemos la consulta para obtener el precio sin importar fechas... solo como referencia
                $weekend = date('l', strtotime($datefrom));
                switch ($weekend) {
                    case "Friday":
                        $sql = "SELECT `room_price_fri` FROM `hotel_room_price` WHERE room_type_id = '$room_type_id' AND `room_person` =  '$Room1' AND `price_deleted` = '0'";
                            $standardprice = mysqli_query($conn, $sql);
                            if (!$standardprice) {
                                die('Could not get data: ' . mysqli_error());
                            //movemos el "while" dentro del "else"
                            } 
                            else {
                                while ($standard = mysqli_fetch_array($standardprice, MYSQLI_ASSOC)) {
                                    $stdrd2 = $standard['room_price_fri'];
                                    echo "$ ";
                                    echo number_format((float)$stdrd2, 2, '.', '');
                                    ?>
                                    <p style="text-align: center;"><span style="font-family: helvetica; color: #ff4c00; font-size: 12px;"><span style="color: rgba(255, 76, 0, 0.63);"><?php echo "10% OFF"; ?></span></span></p>
                                    <?php
                                }
                                mysqli_close($conn); //cerramos la conexión con la base de datos
                            }
                        break;
                    case "Saturday":
                        $sql = "SELECT `room_price_sat` FROM `hotel_room_price` WHERE room_type_id = '$room_type_id' AND `room_person` =  '$Room1' AND `price_deleted` = '0'";
                            $standardprice = mysqli_query($conn, $sql);
                            if (!$standardprice) {
                                die('Could not get data: ' . mysqli_error());
                            //movemos el "while" dentro del "else"
                            } 
                            else {
                                while ($standard = mysqli_fetch_array($standardprice, MYSQLI_ASSOC)) {
                                    $stdrd2 = $standard['room_price_sat'];
                                    echo "$ ";
                                    echo number_format((float)$stdrd2, 2, '.', '');
                                    ?>
                                    <p style="text-align: center;"><span style="font-family: helvetica; color: #ff4c00; font-size: 12px;"><span style="color: rgba(255, 76, 0, 0.63);"><?php echo "10% OFF"; ?></span></span></p>
                                    <?php
                                }
                                mysqli_close($conn); //cerramos la conexión con la base de datos
                            }
                        break;
                    case "Sunday":
                        $sql = "SELECT `room_price_sun` FROM `hotel_room_price` WHERE room_type_id = '$room_type_id' AND `room_person` =  '$Room1' AND `price_deleted` = '0'";
                            $standardprice = mysqli_query($conn, $sql);
                            if (!$standardprice) {
                                die('Could not get data: ' . mysqli_error());
                            //movemos el "while" dentro del "else"
                            } 
                            else {
                                while ($standard = mysqli_fetch_array($standardprice, MYSQLI_ASSOC)) {
                                    $stdrd2 = $standard['room_price_sun'];
                                    echo "$ ";
                                    echo number_format((float)$stdrd2, 2, '.', '');
                                    ?>
                                    <p style="text-align: center;"><span style="font-family: helvetica; color: #ff4c00; font-size: 12px;"><span style="color: rgba(255, 76, 0, 0.63);"><?php echo "10% OFF"; ?></span></span></p>
                                    <?php
                                }
                                mysqli_close($conn); //cerramos la conexión con la base de datos
                            }
                        break;
                    default:
                        $sql = "SELECT `room_price` FROM `hotel_room_price` WHERE room_type_id = '$room_type_id' AND `room_person` =  '$Room1' AND `price_deleted` = '0'";
                            $standardprice = mysqli_query($conn, $sql);
                            if (!$standardprice) {
                                die('Could not get data: ' . mysqli_error());
                            //movemos el "while" dentro del "else"
                            } 
                            else {
                                while ($standard = mysqli_fetch_array($standardprice, MYSQLI_ASSOC)) {
                                    $stdrd2 = $standard['room_price'];
                                    echo "$ ";
                                    echo number_format((float)$stdrd2, 2, '.', '');
                                    ?>
                                    <p style="text-align: center;"><span style="font-family: helvetica; color: #ff4c00; font-size: 12px;"><span style="color: rgba(255, 76, 0, 0.63);"><?php echo "10% OFF"; ?></span></span></p>
                                    <?php
                                }
                                mysqli_close($conn); //cerramos la conexión con la base de datos
                            }
                        break;
                }
        }
}

所以这是我的疑问,论证:$room_type_id是唯一一个我需要在主函数中更改以从数据库中的每个房间获得我想要的东西,并且每个函数都应该与变量作为参数来改变这样的信息...我的问题是,如果我在主变量中定义一次房间类型id,它是否也会被接受并用作所有其他函数作为此参数的值?让我们说:

下一个功能(&#34; 7&#34;);

数字7是否会用作此函数中所有其他嵌套函数作为同一参数的值?

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

  

数字7是否会用作此函数中所有其他嵌套函数作为同一参数的值?

答案是'是'。