在 PHP 中重用代码的最佳方法是什么?

发布于 2024-08-02 06:12:19 字数 1682 浏览 1 评论 0原文

代码:

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 新手,所以一定有比我正在尝试的更简单的方法。

Code:

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

I need to use this code often. The only difference is the array_reverse (..., true) in the first example.

I have tried to solve the problem by making a function organize_question to solve this problem. I was unsuccessful:

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!
      }
  }

I then changed the relevant line in my code to this:

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

The problem is in transferring variables from one function to another.
I tried to put all necessary variables in the parameters of the function, but everything gets broken, since there are many dependencies on this function.

I am new to PHP so there must be easier way to do this than what I am trying.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

九公里浅绿 2024-08-09 06:12:19

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

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

It sounds like this part of your code does the bulk of the work:

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

I would separate the $_GET['tab'] checking out of your organize_questions() function, and do the parameter decisions elsewhere. Like this:

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

And then base your decision making code elsewhere:

  if ( $_GET['tab'] == 'newest' )
  {
    organize_questions(array_reverse ( $end_array ,  true ));
  }
  else if ( $_GET['tab'] == 'oldest' )
  {
      organize_questions($end_array);
  } 
   else
  {
     //etc.
  }
同展鸳鸯锦 2024-08-09 06:12:19

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

使用 include:

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

It's a good question. You can definitely spend a long time just trying out different ways to keep yourself from reusing code. I would probably do one of the function suggestions as listed above, but another option would be to put the code in a separate PHP file and then include it where you want. This basically becomes the equivalent of an inline function in other languages, and if you're worried about speed of execution it's a good way to go. In most cases, however, you will be more worried about the size of page that you're sending the client over http, so this won't be as acceptable as writing a function. I'm mostly pointing out that each situation has a different "best" solution - in your case I'd say McAden's answer is a good one.

Using include:

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

And then in your code later:

//myexecutionplace.php
$end_array = foo;
include 'myscript.php';
doStuffWith($end_array);
$end_array = foo2;
include 'myscript.php';
doStuffWith($end_array2);
尹雨沫 2024-08-09 06:12:19
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 ...它对于调试等很有用。通常,您需要某种方法从数组中挑选您真正想要显示的片段,并对各个片段使用回显或打印。

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

function organize_questions( $tab )
{
    ...
}

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

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

然后您将使用您之前创建的函数中的原始 $tab 或如我所述就在上面参数列表中的 $tab

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

I removed the echos and used print_r (assuming that those variables were actually arrays). Additionally unless you're using $tab somewhere else in the function it was unneeded.

EDIT: I wouldn't actually use print_r...it's useful for debug and such. Usually you'd want some way to pick the pieces from an array that you actually want to display and use echo or print for the individual pieces.

EDIT2: I'm getting both upvoted and downvoted on this. It's rewritten the function in question with correct syntax. Portions of the question are very vague so I'll continue. You seem to also be asking of passing information into functions. the $_GET['tab'] in question is accessing get variables (yoursite.com/index.php?tab=newest). What you seem to be asking with is how to use functions at all. You had it correct going with:

function organize_questions( $tab )
{
    ...
}

Assuming that you were going to use the variable tab. In order to use this function you would call it as such from another function within the file, or another file that does a php_require or php_include:

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

And then you would use the original $tab in the function as you created it earlier or as I stated just above with $tab in the parameter list

清晨说晚安 2024-08-09 06:12:19

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

$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

What you're looking for is a strategy....

$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) );

You're basically saying that you have these things (questions) that you want to do something on (sort them).

You might also want to look at the usort function, http://www.php.net/manual/en/function.usort.php

太阳公公是暖光 2024-08-09 06:12:19
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)
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);

And you should probably rewrite the following.

foreach($array as $tags_and_Qid['question_id'] => $titles_and_Qid['title'] )
//could be rewritten as 
foreach($array as $question_id => $title)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文