2

我了解到 OOP 都是关于数据封装的,但是在彼此无关的类之间传递数据呢(下面的示例是否值得使用extends)?

class Dog {
    private $secretVar;

    public function getSecretVar() {
        $this->secretVar = 'psst... only for rainbow!';
        return $this->secretVar;
    }
}

class Rainbow {
    public function __construct(Dog $Dog) {
        print_r($Dog->getSecretVar());
    }
}

$Dog = new Dog();
$Rainbow = new Rainbow($Dog);

// ... classes that don't need the $secretVar

您将如何$secretVar仅封装类DogRainbow?截至目前,任何人都可以调用getSecretVar(),我很难让这种情况发生,因为它似乎破坏了封装的全部意义。

4

4 回答 4

0

在您的情况下,您可以这样使用protected:(每个扩展 hasSecret 的类都可以访问它。)

<?php
class HasSecret {
    protected $secretVar = 'psst... only for rainbow!';
}

class Dog extends HasSecret {
    public function getSecretVar() {
        return $this->secretVar;
    }
}

class Rainbow extends HasSecret {
    public function __construct(Dog $Dog) {
        print_r($Dog->getSecretVar());
    }
}

$Dog = new Dog();
$Rainbow = new Rainbow($Dog);
于 2012-10-21T22:45:15.650 回答
0

It wouldn't make sense for a Dog to extend Rainbow or vice versa just to share a variable.

What you are asking of may be possible but I don't know. If it was C++ using the friend visibility, it is certainly possible.

In this case, you have to make it public or use a getter and setter.

于 2012-10-21T22:41:08.380 回答
0

Encapsulation is not ment to hide the value of the variable from the rest of the program but to have full control of how the rest of your program can access the variable.

By declaring the variable private you can check what values it can be set to and you can make changes to it before anybody reads it.

There is no real point in trying to let only some of the classes read the variable.

What you are trying to do could be achieved by using reflection to check which class and method calls the getSecretVar() method, but it's hardly ever useful.

于 2012-10-21T22:41:24.810 回答
0

这是一个解决方案,尽管它很难看。

class Dog {
    private $secretVar = 'psst... only for rainbow!';    

    public function getSecretVar($caller == NULL) {

        // Here's the trick...
        if (get_class($caller) == 'Rainbow') {
            return $this->secretVar;
        } else {
            return '';
        }
    }
}

class Rainbow {
    public function __construct(Dog $Dog) {
        print_r($Dog->getSecretVar($this));
    }
}

$Dog = new Dog();
$Rainbow = new Rainbow($Dog);

// ... classes that don't need the $secretVar

它很丑,因为它难以维护且不直观。如果您真的需要这样做,那么您的设计中很可能存在缺陷。

于 2012-10-21T22:50:45.553 回答