-2
class makeAccount {
public $username;
public function __construct ($username,$password) {
    $this->username = $username;
}
public function password($password) {
    if(isset($password)) {
       $this->password = $password;
       return;
    }
  }
}

$user_1 = new makeAccount("abc123","12345");
print $user_1->password("12345");

I am new to php. I am just wondering how to make a private property. I want to have a password property that is private. Is there something wrong with my code?

  • 5
    Instead of using `public $username;` use `private $username;`, that's it. Also, better use google for such basic queries. – Echoes Jun 02 '17 at 16:05
  • 1
    Also, your class names should be nouns, not verbs, and your class methods should be verbs, not nouns. – Mike Jun 02 '17 at 16:08
  • Also, `isset()` should probably be `!empty()` – Jenne Jun 02 '17 at 16:11
  • You can add new properties to objects in your methods, like you're doing with `$this->password = $password;`. However, if they haven't been previously defined with a visibility keyword, (`public`, `private`, or `protected`) like you're doing with `public $username;`, they will be created as public by default. – Don't Panic Jun 02 '17 at 16:12
  • @JennevanderMeer Not necessarily. Maybe the OP wants to allow empty passwords. – Mike Jun 02 '17 at 16:14
  • @Mike well then it can be removed because i'm pretty sure isset is true on a function argument. Hence my assumption on why he probably wanted empty – Jenne Jun 02 '17 at 16:16
  • Actually, neither isset or empty are necessary. If no argument was provided there would already be a fatal error before it got to that check. The only way `isset($password)` could be false is if `null` was passed. Might as well just check `if ($password)` in that case. – Don't Panic Jun 02 '17 at 16:22

1 Answers1

0

you need to use private keyword info about it here http://php.net/manual/en/language.oop5.visibility.php

class makeAccount {
    public $username;
    private $password;
.....
eantonov
  • 26
  • 3