Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error code while trying to use private variables in a function [closed]

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();
like image 271
JoeCortopassi Avatar asked Mar 22 '10 21:03

JoeCortopassi


3 Answers

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'];
like image 59
Alan Storm Avatar answered Oct 30 '22 09:10

Alan Storm


You are declaring a private variable inside a method, which is not possible.

If you want ac to have private variables, you would have to declare them in the class definition:

class ac
{

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

and access them in the class's methods using

public function authentication()
{

 echo $this->plain_username;

By the way, the statement assigning md5_password won't work - you can't use functions in class definitions.

You would have to do the md5 calculation in the class constructor, which would be the cleaner way to do the assignments anyway. In the class, add:

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

and then initialize the class:

 $ac = new ac($_POST["username"], $_POST["password"]);
like image 34
Pekka Avatar answered Oct 30 '22 09:10

Pekka


Public and private are only applied to variables within a class, anywhere else is useless. You cannot request a variable from a function, therefore it can't be defined as public/private/protected. Variables within a function can only have static applied to them (at least that's the only thing I've ever applied to a variable inside a function).

like image 30
animuson Avatar answered Oct 30 '22 08:10

animuson