dongshan1811 2017-08-31 14:23
浏览 89
已采纳

如何使用函数参数PHP

i'm trying to understand the best way to use Function's arguments in nested functions:

Here are my thoughts:

This is a bunch of functions i first declare to use them later in other functions:

//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;
        }

So here is the main function:

//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;
                }
        }
}

So here is my doubt, the argument: $room_type_id is the only one wich i need to change in the main function to get what i want from every room in the database, and each function should be used with that variable as parameter to change such information... my question is, if i define the room type id once in the main variable, will this be also accepted and used for all the others functions as a value for this argument? lets say:

function next("7");

Will the number 7 be used for all the other nested functions inside this function as a value for the same argument?

Thanks in advance for your help.

  • 写回答

1条回答 默认 最新

  • doulou1989 2017-08-31 14:30
    关注

    Will the number 7 be used for all the other nested functions inside this function as a value for the same argument?

    The answer is 'yes'.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler