如何在 Laravel Eloquent 模型中将 属性 设为私有?
How do I make a property private in a Laravel Eloquent Model?
似乎太明显了,但是我如何将 class 属性 设为私有:
class User extends Model
{
private $name; // or protected
}
$user = new User();
$user->name = "Mrs. Miggins"; // <- I want this to generate an error
echo $user->name; // Mrs. Miggins, (this too)
这是Laravel 5.1
尝试覆盖 __get(){}
和 __set(){}
魔术方法,所以它会是这样的:
class User extends Model
{
protected $privateProperties = ['name'];
public function __get($varName) {
$this->isPrivate($varName);
return parent::__get($varName);
}
public function __set($varName, $value) {
$this->isPrivate($varName);
return parent::__set($varName, $value);
}
protected function isPrivate($varName) {
if (in_array($varName, $this->privateProperties)) {
throw new \Exception('The ' . $varName. ' property is private');
}
}
}
似乎太明显了,但是我如何将 class 属性 设为私有:
class User extends Model
{
private $name; // or protected
}
$user = new User();
$user->name = "Mrs. Miggins"; // <- I want this to generate an error
echo $user->name; // Mrs. Miggins, (this too)
这是Laravel 5.1
尝试覆盖 __get(){}
和 __set(){}
魔术方法,所以它会是这样的:
class User extends Model
{
protected $privateProperties = ['name'];
public function __get($varName) {
$this->isPrivate($varName);
return parent::__get($varName);
}
public function __set($varName, $value) {
$this->isPrivate($varName);
return parent::__set($varName, $value);
}
protected function isPrivate($varName) {
if (in_array($varName, $this->privateProperties)) {
throw new \Exception('The ' . $varName. ' property is private');
}
}
}