왜 구성보다는 상속을 선호하는 리팩토링 정말, 전부 그 this->theMethod();
Abstract class A
{
public function renderSomethingRecursive()
{
$this->renderSomethingRecursive(); // no need for self::, that's for static calls
}
abstract public function addSomething (value);
}
class B extends A
{
public function addSomething (value)
{
$this->renderSomethingRecursive();//calls the abstract method as though it were defined in class B
}
}
를 사용하여 호출 할 수 있습니다? '무언가 추가'와 '재귀 적 무언가'를 별도의 관심사로 나누기 시작하면 함께 잘 어울리는 작고 이해하기 쉬운 수업을 찾을 수 있습니다.
B
의 발신자가 renderSomethingRecursive()
에 전화를 걸 수 없으므로 클래스에서 기능을 완전히 제거하십시오. 또한 상속을 깨고, B
은 A
에서 상속 할 필요가 없습니다. 우리는 여전히 B
에 'stuff stuff'을 추가하여 addSomething()
이라는 기능을 유지하려고합니다. 두 클래스에서 addSomething
의 본문을 복제하고 싶지 않으므로 이 호출 될 때마다 A
의 인스턴스에 위임하도록 B
을 가져올 수 있습니다.
abstract class A
{
public function renderSomethingRecursive()
{
// this function can call itself
self::renderSomethingRecursive();
}
abstract function addSomething ($value) {
}
class AA extends A
{
public function addSomething($value)
{
// something, something, something....
self::renderSomethingRecursive();
}
}
class B
{
private $a;
public function __construct(A $a)
{
$this->a = $a;
}
public function addSomething ($value) {
$this->a->addSomething($value);
}
}
$obj = new B(new AA());
$obj->addSomething(....);
이 더 나은 이미지고, 그러나 우리는 우리가 완료되기 전에 addSomething
중복이 제거 할 수 있습니다. 목록을 렌더링하고 관리하는 것은 실제로 두 가지 다른 관심사이므로이를 분할 할 수 있습니다. 먼저 addSomething
을 B
으로 옮깁니다. 그런 다음 renderSomethingRecursive
이 $ 데이터에 대한 액세스 권한을 필요로 함을 알고 있습니다. 일부 매개 변수를 추가하여 해당 데이터에 다시 액세스 할 수 있습니다. A
은 더 이상 추상적 일 필요는 없지만 의 구현이 여전히 다른 경우 일 수 있습니다. B
일 수 있습니다. 코드가 결코 B : renderSomethingRecursive는()`(I은 충분히 실행 얻을를 수정 한`호출하지, 즉 제거`값 - 당신은 ...이 같은 뭔가
class A
{
public function renderSomethingRecursive($data)
{
// this function can call itself
self::renderSomethingRecursive($data);
}
}
class B
{
private $a;
private $data;
public function __construct(A $a)
{
$this->a = $a;
}
public function addSomething ($value) {
// something, something, something....
// append to $this->data probably
$this->a->renderSomethingRecursive($this->data);
}
}
$obj = new B(new AA());
$obj->addSomething(....);
재현 할 수 없습니다 두어야합니다 ','A'를 '추상'이라고 선언했다. – lanzz
재생할 수 없습니다. 귀하의 질문은 무엇인가? – hakre
실제 코드를 게시하십시오.이 코드는 구문 오류로 인해 실행되지 않습니다. 그것은 결코 B에서 메서드를 실행해서는 안되므로 명백하게 뭔가 잘못하고 있지만이 코드는 보이지 않습니다. –