Clone davranış - klon için öznitelik değerini ayarlamak değil mi?

2 Cevap php

Beklendiği gibi bu kod çalışmaz:

// $field contains the name of a subclass of WMSInput.
$fieldClone = clone $field;

echo $fieldClone->getInputName();

// Method on abstract WMSInput superclass.
$fieldClone->setInputName( 'name' );

echo $fieldClone->getInputName();

WMSInput class:

abstract class WMSInput {
  private $inputName;

  public function setInputName( $inputName ) {
    $this->inputName = $inputName;
  }
}

Hayır PHP hataları (hata raporlama E_ALL ayarlanır) vardır.

Actual Results

email
email

Expected Results

email
name

Herhangi bir fikir?

2 Cevap

Benim test sitesinde Tamam çalıştı.

Sizin örnekte yöntem getInputName kopyalanamaz değil. Ben orada aramaya başlamak istiyorum. Belki istenen değişken değil dönmek?

Benim test kodu oldu:

<?php

abstract class WMSInput {
  private $inputName;

  public function setInputName( $inputName ) {
    $this->inputName = $inputName;
  }

  public function getInputName() {
    return $this->inputName;
  }
}

class Test extends WMSInput {
}

$field = new Test();

$field->setInputName('email');

// $field contains the name of a subclass of WMSInput.
$fieldClone = clone $field;

echo $fieldClone->getInputName();

// Method on abstract WMSInput superclass.
$fieldClone->setInputName( 'name' );

echo $fieldClone->getInputName();

Çıktı:

emailname

hangi doğru.

Biraz :) debuging yankı

  1. set InputName atamadan önce $ inputName echo
  2. set InputName atamadan önce $ this-> inputName echo
  3. set InputName atandıktan sonra $ this-> inputName echo

Ayrıca soyut olarak bu sınıf varsa o ana sınıflarında bu yöntemle erişim olmazdı, korunan inputName özelliğini ayarlamayı deneyin