phpphp-parse-error

Error code while trying to use private variables in a function


I get an error that says

Parse error: syntax error, unexpected T_PRIVATE in E:\PortableApps\xampp\htdocs\SN\AC\ACclass.php on line 6

while trying to run my script. I'm new to classes in PHP and was wondering if someone could point out my error. Here's the code for that part.

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

    $ac = new ac();

Solution

  • You don't define class properties (public/private/etc) in functions/methods. You do it in the body of the class.

    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();
    

    If you want to define variables in a function/method, just declare them without the public/private/protected

    $plain_username = $_POST['username'];