2010-04-15 78 views
3

此代码不能按预期:克隆行为 - 无法为克隆设置属性值?

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

在我的测试网站上,它工作正常。

您的示例中没有复制方法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 

这是正确的。

0

回声调试运行了一点:)

  1. 在集InputName呼应$ inputName之前设定的分配
  2. 前集InputName呼应的分配
  3. InputName呼应$这个 - > inputName $ this-> inputName分配后

也尝试将inputName属性设置为受保护的,如果您将该类作为抽象类,那么在父类中您将无法访问该方法od

+0

但他使用公共方法(访问器)来获取/设置此属性。这是对的。 – 2010-04-15 07:54:50

+0

我添加了很多用于调试的echo语句。当在'setInputName'方法中,'inputName'变量设置正确。该值在离开该方法后立即恢复。令人费解。 – 2010-04-15 16:14:35