【问题标题】:What is the best way to reuse code in PHP?在 PHP 中重用代码的最佳方法是什么?
【发布时间】:2010-11-21 00:04:05
【问题描述】:

代码:

if ( $_GET['tab'] == 'newest' ) { 
      // Go through each question
      foreach( array_reverse( $end_array, true ) as $tags_and_Qid['question_id'] => $titles_and_Qid['title'] )
      {   
        // Grab the title for the first array
        $title = $titles [ $tags_and_Qid['question_id'] ] ['title'];

        // Grab the tags for the question from the second array
        $tags = $end_array [ $tags_and_Qid['question_id'] ] ['tag'];

        // Grab the username for the question from the second array
        $username = $usernames [ $tags_and_Qid['question_id'] ] ['username'];
        --- cut ----                                                                                                                                                       
      }   
  }

我需要经常使用此代码。唯一的区别是第一个示例中的array_reverse (..., true)

我已尝试通过创建函数organize_question 来解决此问题。我失败了:

function organize_questions ( $tab ) {
      if ( $_GET['tab'] == 'newest' ) {
        echo ( "array_reverse ( $end_array ,  true )" ); 
                                  // Problem here!
      }
      if ( $_GET['tab'] == 'oldest' ) {
          echo ( "$end_array" );    
            // this does not work
      } else {
        echo ( "array_reverse ( $end_array ,  true )" );
                                   // Problem here!
      }
  }

然后我将代码中的相关行更改为:

 foreach( organize_question( $tab ) as $tags_and_Qid['question_id'] => $titles_and_Qid['title'] )

问题在于将变量从一个函数转移到另一个函数。
我试图将所有必要的变量放在函数的参数中,但一切都被破坏了,因为这个函数有很多依赖项。

我是 PHP 新手,所以必须有比我尝试的更简单的方法。

【问题讨论】:

  • 重用代码的最佳方式?不使用PHP!哦,我的孩子,我的孩子......

标签: php code-reuse


【解决方案1】:

听起来您的这部分代码完成了大部分工作:

  // Go through each question
  foreach( array_reverse( $end_array, true ) as $tags_and_Qid['question_id'] => $titles_and_Qid['title'] )
  {   
          -- cut ---
  }

我会将$_GET['tab']organize_questions() 函数分开,并在其他地方进行参数决策。像这样:

function organize_questions($array)
{
    foreach($array as $questionId => $title )
      {   
            //do the work
      }   
}

然后将您的决策代码基于其他地方:

  if ( $_GET['tab'] == 'newest' )
  {
    organize_questions(array_reverse ( $end_array ,  true ));
  }
  else if ( $_GET['tab'] == 'oldest' )
  {
      organize_questions($end_array);
  } 
   else
  {
     //etc.
  }

【讨论】:

  • 这是比 McAden 的答案更好的方法。当您不再处理 $_GET['tab'] 时,您可能希望使用该函数。
  • 我目前有 7 个数组作为函数的参数。这对于处理数据非常低效。所有数组的形式都是数组['question_id']['x'],其中 x 是给定对象,例如标题或标签,在这种情况下,['x'] 实际上是 ['x'][]。 如何将数组合并为两个数组:data_A['id']['x'] 和 data_B['id']['x'][]?
【解决方案2】:

这是个好问题。您绝对可以花很长时间尝试不同的方法来阻止自己重用代码。我可能会执行上面列出的功能建议之一,但另一种选择是将代码放在单独的 PHP 文件中,然后将其包含在您想要的位置。这基本上相当于其他语言中的内联函数,如果您担心执行速度,这是一个不错的选择。但是,在大多数情况下,您会更担心通过 http 向客户端发送的页面大小,因此这不像编写函数那样可以接受。我主要是指出每种情况都有不同的“最佳”解决方案 - 在您的情况下,我会说 McAden 的答案是一个很好的解决方案。

使用包括:

//myscript.php
if ( $_GET['tab'] == 'newest' ) 
{
    print_r( array_reverse( $end_array ,  true ) ); 
}
else if ( $_GET['tab'] == 'oldest' ) 
{
    print_r($end_array);    
} 
else 
{
    print_r(array_reverse ( $end_array ,  true ) );
}

然后在您的代码中:

//myexecutionplace.php
$end_array = foo;
include 'myscript.php';
doStuffWith($end_array);
$end_array = foo2;
include 'myscript.php';
doStuffWith($end_array2);

【讨论】:

    【解决方案3】:
    function organize_questions () 
    {
        if ( $_GET['tab'] == 'newest' ) 
        {
            print_r( array_reverse( $end_array ,  true ) ); 
        }
        else if ( $_GET['tab'] == 'oldest' ) 
        {
            print_r($end_array);    
        } 
        else 
        {
            print_r(array_reverse ( $end_array ,  true ) );
        }
    }
    

    我删除了回声并使用了 print_r(假设这些变量实际上是数组)。此外,除非您在函数的其他地方使用 $tab,否则它是不需要的。

    编辑:我实际上不会使用 print_r ...它对调试等很有用。通常,您需要某种方式从数组中挑选出您真正想要显示的片段,并为各个片段使用 echo 或 print。

    EDIT2:我对此表示赞同和反对。它用正确的语法重写了有问题的函数。问题的某些部分非常模糊,所以我将继续。您似乎还要求将信息传递给函数。有问题的 $_GET['tab'] 正在访问获取变量(yoursite.com/index.php?tab=newest)。您似乎要问的是如何使用函数。你说得对:

    function organize_questions( $tab )
    {
        ...
    }
    

    假设您要使用变量选项卡。为了使用这个函数,你可以从文件中的另一个函数或另一个执行 php_require 或 php_include 的文件中调用它:

    $mytab = 'bob';
    organize_questions( $mytab);
    

    然后你会在函数中使用原来的 $tab,就像你之前创建的那样,或者像我上面所说的那样,在参数列表中使用 $tab

    【讨论】:

      【解决方案4】:

      您正在寻找的是一种策略....

      $strategies = array(
        'oldest' => create_function(
            '$questions', 
            'return organize_questions($questions);'
        ),
        'hottest' => create_function(
            '$questions', 
            'return organize_questions(sort_by_hottness($questions));'
        ),
        'default' => create_function(
            '$questions', 
            'return organize_questions(array_reverse($questions, true));'
        ),
      );
      
      $strategy = 'default';
      
      if (array_key_exists($strategies, $_GET['tab'])
          $strategy = $_GET['tab'];
      
      print_r( $strategies[$strategy]($questions) );
      

      你基本上是在说你有这些事情(问题)你想对它们做些什么(排序)。

      您可能还想查看 usort 函数,http://www.php.net/manual/en/function.usort.php

      【讨论】:

        【解决方案5】:
        function sortArray($direction, $array)
        {
            switch ($direction) { 
                case 'oldest':
                    return array_reverse($array, true);
                case 'newest':
                    return $array;
                default:
                    return array(); 
            }
        }
        
        function processQuestions($array)
        {
            foreach($array as $tags_and_Qid['question_id'] => $titles_and_Qid['title'] ) {   
                //code
            } 
        }
        
        $sortedArray = sortArray($tab, $end_array);
        processQuestions($sortedArray);
        

        你可能应该重写以下内容。

        foreach($array as $tags_and_Qid['question_id'] => $titles_and_Qid['title'] )
        //could be rewritten as 
        foreach($array as $question_id => $title)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-30
          • 1970-01-01
          • 2011-02-22
          • 2022-01-19
          • 2020-10-11
          • 2012-09-01
          相关资源
          最近更新 更多