【发布时间】:2017-06-02 16:04:05
【问题描述】:
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");
我是 php 新手。我只是想知道如何制作私有财产。我想要一个私有的密码属性。我的代码有问题吗?
【问题讨论】:
-
不要使用
public $username;使用private $username;,就是这样。此外,最好使用 google 进行此类基本查询。 -
另外,你的类名应该是名词,而不是动词,你的类方法应该是动词,而不是名词。
-
另外,
isset()应该是!empty() -
您可以在方法中为对象添加新属性,就像使用
$this->password = $password;一样。但是,如果之前没有使用可见性关键字(public、private或protected)定义它们,就像您使用public $username;所做的那样,它们将默认创建为公共。跨度> -
@JennevanderMeer 不一定。也许 OP 想要允许空密码。