我如何用我的代码定义一个PHP函数

问题描述 投票:-2回答:4

我有这个代码,计算一个字符串accorances我只是无法解释我的用途,但它真的很好我看到这里请看这里https://ideone.com/pvAIjW

码:

  <?php
   $te = 'abcdefghijklmnopqrstuvwxyz1234567891011121314151617181920';

  $text=strlen($te);
  if($text <=10)       
  { 
  $g == 2;
  }
  else
  {
   $x=$text;
  $y=2;
  $tempMod = (float)($x / $y);
  $tempMod = ($tempMod - (int)$tempMod)*$y;
  if($tempMod ==0)
  {
  $g = $x / $y;
  }
  else
  {
  $x = $x+1;
  $g = $x / $y;
  }
  }
  echo $g;

在我的成就中,我希望它作为一个函数,所以我只需要调用$ output = function($ string); echo $ output得到我的结果

非常感谢提前

php string function output
4个回答
-2
投票

只需要将$ te变量作为参数发送到函数:

function fnct($te){
     $text=strlen($te);
     if($text <=10)       
     { 
         $g == 2;
     }else{
         $x=$text;
         $y=2;
         $tempMod = (float)($x / $y);
         $tempMod = ($tempMod - (int)$tempMod)*$y;
         if($tempMod ==0)
         {
             $g = $x / $y;
         }else{
            $x = $x+1;
            $g = $x / $y;
         }
     }
     return $g;
}

当你想调用这个函数时,你将使用这个代码:

$te = 'abcdefghijklmnopqrstuvwxyz1234567891011121314151617181920';
$output = fnct($te);
echo $output;

2
投票

那会是这样的。只需更改$te的所有实例(尽管你仍然可以使用$te,如果你想,我只是改变它以避免混淆)使用参数名称(这是$ string),然后返回它而不是回显$g

function functionName($string){
    $text=strlen($string);
    if($text <=10)       
    { 
        $g == 2;
    }
    else
    {
        $x=$text;
        $y=2;
        $tempMod = (float)($x / $y);
        $tempMod = ($tempMod - (int)$tempMod)*$y;
        if($tempMod ==0)
        {
            $g = $x / $y;
        }
        else
        {
            $x = $x+1;
            $g = $x / $y;
        }
     }
     return $g;
}
$te = 'abcdefghijklmnopqrstuvwxyz1234567891011121314151617181920';
$varName = functionName($te);

注意:不要粗鲁,但这种问题很容易搜索,所以我建议你尝试阅读有关PHP的文档或查找在线教程,大部分时间他们都会介绍使用和创建函数


0
投票
<?php
   $te = 'abcdefghijklmnopqrstuvwxyz1234567891011121314151617181920';

function name($value){

    $text=strlen($value);
    if($text <=10){
        $value == 2;
    }
    else{
      $x=$text;
      $y=2;
      $tempMod = (float)($x / $y);
      $tempMod = ($tempMod - (int)$tempMod)*$y;
      if($tempMod ==0){
        $g = $x / $y;
      }else{
        $x = $x+1;
        $value = $x / $y;
      }
    }
      return $value;

}
echo name($te);

0
投票
function functionName($string){
    if(strlen($string) <=10) $g == 2;
    else {
        $x=strlen($string);
        $y=2;
        if(!(((float)($x / $y) - (int)((float)($x / $y)))*$y ==0)) $x++;
        $g = $x / $y;
     }
     return $g;
}
$te = 'abcdefghijklmnopqrstuvwxyz1234567891011121314151617181920';
$varName = functionName($te);
var_dump($varName);

代码可能会更短。由你决定。

© www.soinside.com 2019 - 2024. All rights reserved.