Dave Jarvis
Dave Jarvis

Reputation: 31211

Clone behaviour - cannot set attribute value for clone?

This code does not function as expected:

// $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();

The WMSInput class:

abstract class WMSInput {
  private $inputName;

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

There are no PHP errors (error reporting is set to E_ALL).

Actual Results

email
email

Expected Results

email
name

Any ideas?

Upvotes: 3

Views: 168

Answers (2)

Gabriel Solomon
Gabriel Solomon

Reputation: 30085

echo debuging a little :)

  1. in set InputName echo the $inputName before the assign
  2. in set InputName echo the $this->inputName before the assign
  3. in set InputName echo the $this->inputName after the assign

also try setting the inputName property to protected, if you have that class as abstract then in the parent classes you would not have access to that method

Upvotes: 0

Tomasz Struczyński
Tomasz Struczyński

Reputation: 3303

On my test site it worked ok.

You haven't copied method getInputName in your example. I'd start searching in there. Maybe you return not the desired variable?

My test code was:

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

Output:

emailname

which is correct.

Upvotes: 2

Related Questions