gpt4 book ai didi

php - __get() 和 __set() 是否意味着泄漏封装?

转载 作者:可可西里 更新时间:2023-11-01 00:44:29 25 4
gpt4 key购买 nike

在 OO 编程中,使用魔法方法 __get()__set() 会不会被人看不起,这些会导致类的封装泄漏吗?例如:

class User {
private $username;
private $password;

public function __set($name,$value) {
$this->$name = $value;
}

public function __get($name) {
return $this->$name;
}
}

这有效地使private/protected 变量public

最佳答案

您的代码:

class User {
private $username;
private $password;

public function __set($name,$value) {
$this->$name = $value;
}

public function __get($name) {
return $this->$name;
}
}

在这种情况下完全没有必要。

封装does not mean “一群 setter和getter ”。您可以将其重构为:

class User {
public $username;
public $password;
}

并且就封装而言,它们是等价的。

一般来说,__get__set 有一些用途,但如果你可以不用,你应该这样做(特别是考虑到它们比普通方法定义要 "considerably slower")。

关于php - __get() 和 __set() 是否意味着泄漏封装?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24020097/

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