gpt4 book ai didi

php - 如何在 Laravel Eloquent 模型中将属性设为私有(private)?

转载 作者:行者123 更新时间:2023-12-04 13:40:28 24 4
gpt4 key购买 nike

似乎太明显了,但我如何将类属性设为私有(private):

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');
}
}
}

关于php - 如何在 Laravel Eloquent 模型中将属性设为私有(private)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40331167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com