1

For example if statement

if($number == 1){
echo '$number == 1';
}

Such statement need to call multiple times. And possibly latter the statement need to change.

Can place this code in external file and the use include.

But better would be create variable something like

$variable = if($number == 1){
echo '$number == 1';
}

This does not work. Tried with ( ), " ". No success.

Any ideas? Is it possible at all?

Updated question

Writing one more time for those who write that question is not understandable.

So need this code if($number == 1){ echo '$number == 1'; } (actually code is much longer) to repeat some 30 times.

And time after time some part of code manually would need to change.

One way how can I do it is to place the code in external file, for example external_file.php and then use require($_SERVER['DOCUMENT_ROOT'] . "/external_file.php");.

Instead of including external content would want to define/create (now I see that need function).

Hope now is clear what I want.

Thanks for answers, will experiment.

4

5 回答 5

1

请使用功能以实现可重用性

function reuseFun($num){
  if($num == 1){
    return 'Number = 1';
  }
  else{
    return 'Number != 1';
  }
}

echo reuseFun(1);
于 2013-08-01T08:20:13.707 回答
1

也许像这样?

function checkNumber($number) {
  if($number == 1){
     return true;
  }
}

然后你可以像这样使用它:

if (checkNumber(1)) {
   echo 'something';
}
于 2013-08-01T08:20:34.270 回答
1

使用功能:

function myTest($number) {
  if($number == 1){
    echo '$number == 1';
  }
}
于 2013-08-01T08:21:19.437 回答
0

那是行不通的,但你可以试试这个:

if($number == 1) {
    $variable = 'number is 1';
} elseif($number == 2) {
    $variable = 'number is 2';
}

echo $variable;
于 2013-08-01T08:18:33.180 回答
0

不清楚 if 语句需要什么,但是如果您需要 if 的简写形式,请使用以下代码。

 echo 'text '. ($number == 1 ? '$number == 1' : 'something else'). ' text';

更多示例

如果您需要重用代码,只需将此代码放入函数中,如下所示,

function print_number($number){
   echo 'text '. ($number == 1 ? '$number == 1' : 'something else'). ' text';
}
于 2013-08-01T09:47:15.527 回答