4

我只是在学习 PHP 课程,所以我在搞乱它。我只是试图从用户那里获取一个值并使用一个类来显示它。但是,当我尝试$_POST在类中使用变量时,它会显示错误。

这是代码:

<form action="classess.php" method="POST" >
<b>Enter the rate : </b>
<input type="text" name="price" />
<input name="submit" type="submit" value="Click" />
</form>
<?php

class rating
{
  public $rate = $_POST['price'];
  public function Display()
  {
    echo $this -> rate;
  }
}

$alex = new rating;
$alex ->Display();
?>
4

4 回答 4

20

您不能在属性定义中包含语句。改用构造函数:

class Rating {
    public $rate;

    public function __construct($price) {
        $this->$rate = $price;
    }

    public function display() {
        echo $this->rate;
    }
}

$alex = new Rating($_POST['price']);
$alex->display();

几点:

  • 不要让自己难受。如果您需要一些东西来使类工作,请在构造函数中询问它。
  • ClassNames通常用大写methodNames字母写,用驼峰写。
  • display()函数可能更可取的是实际return速率,而不是echoing 它。您可以使用返回值做更多的事情。
于 2013-07-09T13:34:18.563 回答
2

这是您正确的 HTML 部分

<form action="classess.php" method="POST" >
<b>Enter the rate : </b>
<input type="text" name="price" />
<input name="submit" type="submit" value="Click" />
</form>

这是您更正的 PHP 部分

<?php
class Rating
{
  public $rate;
  public function __construct() {
    $this->$rate = $_POST['price'];
  }
  public function display()
  {
    echo $this -> rate;
  }
}

$alex = new rating;
$alex ->Display();
?>

让我解释一下。。

public function __construct() {
    $this->rate = $_POST['price'];
  }

正在设置你的变量,即构建类..

public function display()
  {
    return $this->rate;
  }

类中的这个函数实际上得到了 var $rate 的值

$alex = new rating;
echo $alex->display();

然后只需初始化类并使用该函数。

于 2013-07-09T13:43:33.667 回答
1

您试图在错误的位置分配值。您需要在构造函数中分配您的值。

为什么不这样做呢?

<form action="classess.php" method="POST" >
<b>Enter the rate : </b>
<input type="text" name="price" />
<input name="submit" type="submit" value="Click" />
</form>
<?php

class rating
{
  var $rate;

  function rating($price)
  {
    $this->rate = $price;
  }

  public function Display()
  {
    echo $this->rate;
  }
}

$alex = new rating($_POST['price']);
$alex->Display();
?>

这样,您可以在创建对象时初始化值。它为您提供了更多的灵活性。

于 2013-07-09T13:37:38.087 回答
0
<?php
    class rating
    {
      public $rate;
    }

    $alex = new rating;
    $alex->rate=$_POST['price'];
?>

用这种方法就可以简单地得到结果。

于 2017-03-28T10:42:55.800 回答