相关疑难解决方法(0)

为什么要使用getter和setter/accessors?

使用getter和setter的优点是什么 - 只能获取和设置 - 而不是简单地使用公共字段来存储这些变量?

如果getter和setter做的不仅仅是简单的get/set,我可以非常快地解决这个问题,但我并不是100%清楚如何:

public String foo;
Run Code Online (Sandbox Code Playgroud)

更糟糕的是:

private String foo;
public void setFoo(String foo) { this.foo = foo; }
public String getFoo() { return foo; }
Run Code Online (Sandbox Code Playgroud)

而前者需要很少的样板代码.

java oop getter setter abstraction

1472
推荐指数
26
解决办法
37万
查看次数

最佳实践:PHP Magic Methods __set和__get

可能重复:
魔术方法是PHP的最佳实践吗?

这些都是简单的例子,但想象一下你的班级中有两个以上的属性.

什么是最佳做法?

a)使用__get和__set

class MyClass {
    private $firstField;
    private $secondField;

    public function __get($property) {
            if (property_exists($this, $property)) {
                return $this->$property;
            }
    }

    public function __set($property, $value) {
        if (property_exists($this, $property)) {
            $this->$property = $value;
        }
    }
}

$myClass = new MyClass();

$myClass->firstField = "This is a foo line";
$myClass->secondField = "This is a bar line";

echo $myClass->firstField;
echo $myClass->secondField;

/* Output:
    This is a foo line
    This is a bar line
 */
Run Code Online (Sandbox Code Playgroud)

b)使用传统的二传手和吸气剂

class MyClass {

    private $firstField; …
Run Code Online (Sandbox Code Playgroud)

php magic-methods

121
推荐指数
3
解决办法
11万
查看次数

标签 统计

abstraction ×1

getter ×1

java ×1

magic-methods ×1

oop ×1

php ×1

setter ×1