5

我收到一条错误消息

解析错误:语法错误,第 6 行 E:\PortableApps\xampp\htdocs\SN\AC\ACclass.php 中的意外 T_PRIVATE

在尝试运行我的脚本时。我是 PHP 类的新手,想知道是否有人能指出我的错误。这是该部分的代码。

<?php
class ac
  {
  public function authentication()
    {
    private $plain_username = $_POST['username'];
    private $md5_password = md5($_POST['password']);

    $ac = new ac();
4

3 回答 3

15

您没有在函数/方法中定义类属性(公共/私有/等)。你在课堂上做这件事。

class ac
{
    private $plain_username;
    private $md5_password;

    public function authentication()
    {
        $this->plain_username = $_POST['username'];
        $this->md5_password = md5($_POST['password']);
    }
}

//declare a class outside the class
$ac = new ac();

如果您想在函数/方法中定义变量,只需声明它们而不使用 public/private/protected

$plain_username = $_POST['username'];
于 2010-03-22T21:58:09.440 回答
3

private在方法中声明了一个变量,这是不可能的。

如果你想ac拥有私有变量,你必须在类定义中声明它们:

class ac
{

  private $plain_username = $_POST['username'];
  private $md5_password = md5($_POST['password']);

并在类的方法中使用

public function authentication()
{

 echo $this->plain_username;

顺便说一句,赋值语句md5_password不起作用——你不能在类定义中使用函数。

您必须md5在类构造函数中进行计算,无论如何这将是进行分配的更简洁的方法。在类中,添加:

function __construct ($plain_username, $password)
 {
   $this->plain_username = $plain_username;
   $this->md5_password = md5 ($password);
 }

然后初始化类:

 $ac = new ac($_POST["username"], $_POST["password"]);
于 2010-03-22T21:56:04.340 回答
1

public 和 private 仅适用于类中的变量,其他任何地方都无用。您不能从函数请求变量,因此不能将其定义为公共/私有/受保护。函数内的变量只能对它们应用静态(至少这是我唯一应用于函数内变量的东西)。

于 2010-03-22T22:00:24.610 回答