Error code when trying to use private variables in a function

I get an error

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

when trying to run my script. I am new to PHP classes and was wondering if anyone could point out my error. Here is the code for this part.

<?php class ac { public function authentication() { private $plain_username = $_POST['username']; private $md5_password = md5($_POST['password']); $ac = new ac(); 
+4
source share
3 answers

You do not define class properties (public / private / etc) in functions / methods. You do this in the body of the class.

 class ac { private $plain_username; private $md5_password; public function authentication() { private $this->plain_username = $_POST['username']; private $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, simply declare them without public / private / protected

 $plain_username = $_POST['username']; 
+14
source

You declare a private variable inside the method, which is not possible.

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

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

and access them in class methods using

 public function authentication() { echo $this->plain_username; 

By the way, the operator assigning md5_password will not work - you cannot use functions in class definitions.

You will need to do the md5 calculation in the class constructor, which would be a cleaner way of doing assignments. 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"]); 
+3
source

Public and private only apply to variables within the class, somewhere else is useless. You cannot request a variable from a function, therefore it cannot be defined as public / private / protected. Variables inside a function can only be used by static applications (at least this is the only thing I've ever applied to a variable inside a function).

+1
source

Source: https://habr.com/ru/post/1304814/


All Articles