【问题标题】:adding arguments in a PHP在 PHP 中添加参数
【发布时间】:2014-04-01 08:08:43
【问题描述】:

我对 PHP 很陌生,我希望这里有人可以帮助我。我需要写一个类,当下面的页面呼应它时,它会显示答案。

<?php
include_once('Math.php');

$Math = new _Math();

echo $Math->calculate(2,3,"+")."<br />";
echo $Math->calculate(2,3,"-")."<br />";
echo $Math->calculate(2,3,"*")."<br />";
echo $Math->calculate(9,3,"/")."<br />";
echo $Math->calculate(9,0,"/")."<br />";
echo $Math->calculate("3",3,"+")."<br />";
echo $Math->calculate(2.5,3,"+")."<br />";
echo $Math->calculate(3,3,"test")."<br />";

我认为下面的代码可以工作,但我得到的只是一个空白屏幕。

<?php

class _Math {

 function calculate(2,3,"+"){
     $x = 2 + 3;
      return $x;
 }

 function calculate(2,3,"-"){
      $x = 2 - 3;
      return $x;
 }

 function calculate(2,3,"*"){
      $x = 2 * 3;
      return $x;
 }

 function calculate(9,3,"/"){
      $x = 9 / 3;
      return $x;
 }

 function calculate(9,0,"/"){
      $x = 9 / 0;
      return $x;
 }

 function calculate("3",3,"+"){
      $x = "3"+3;
      return $x;
 }

 function calculate(2.5,3,"+"){
      $x = 2.5+3;
      return $x;
 }

 function calculate(3,3,"test"){
      $x = 3 test 3;
      return $x;
 }

我希望有人能指出我正确的方向。希望我离我不远。提前致谢。

【问题讨论】:

  • 你有 x 个计算函数
  • @JakeN 是的,它闻起来像个可怕的老师。
  • 阅读任何 PHP 文档都会给你答案。

标签: php function class arguments


【解决方案1】:

函数参数必须是变量,而不是表达式,这在the manual中有解释。

这是部分实现:

class _Math 
{
    function calculate($op1, $op2, $type)
    {
        switch ($type) {
            case '+': 
                return $op1 + $op2;

            case '-':
                return $op1 - $op2;
            // ... 
        }
    }
}

在函数内部编写一个switch,它将根据$type 参数返回结果。

【讨论】:

    【解决方案2】:

    你的函数应该是这样的

    function calculate(num1, num2, operation){
        switch(operation){
             case '+': 
                  return $num1 + $num2; 
             break;
             case '*':
                  return $num1 * $num2; 
             break;
    
             // continue here :)
    
        }
    
    
    }
    

    您只需要 1 个函数。并且多个同名函数会在 PHP 中抛出错误。

    【讨论】:

      【解决方案3】:

      这不是你定义函数的方式。我什至不确定你想做什么。

      圆括号包含您传递给函数的参数。所以你调用这样的函数:

      $Math->calculate(2,3,"+")
      

      最后三件事是参数。您必须像这样定义函数:

      function calculate($x, $y, $operation){
          //your code
      }
      

      你不能定义多个同名的函数,所以你必须检查操作并根据输入计算它。例如+

      function calculate($x, $y, $operation){
          if($operation === "+") {
              return $x + $y;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-03-24
        • 1970-01-01
        • 2023-03-25
        • 2011-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-06
        相关资源
        最近更新 更多