克隆行为 - 无法为克隆设置属性值?

时间:2010-04-15 07:37:04

标签: php clone

此代码无法正常运行:

// $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类:

abstract class WMSInput {
  private $inputName;

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

没有PHP错误(错误报告设置为E_ALL)。

实际结果

email
email

预期结果

email
name

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

在我的测试网站上,它运行正常。

您没有在示例中复制方法getInputName。我开始在那里搜索。也许你没有返回所需的变量?

我的测试代码是:

<?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();

输出:

emailname

这是正确的。

答案 1 :(得分:0)

回声有点喘息:)

  1. in set InputName在assign
  2. 之前回显$ inputName
  3. in set InputName在assign
  4. 之前回显$ this-&gt; inputName
  5. in set InputName在assign
  6. 之后回显$ this-&gt; inputName

    还尝试将inputName属性设置为protected,如果您将该类设置为abstract,那么在父类中您将无法访问该方法

相关问题