Clone behavior - can't set attribute value for clone?

This code does not work properly:

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

Grade WMSInput:

abstract class WMSInput {
  private $inputName;

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

No PHP errors (error messages set to E_ALL).

Actual Results

email
email

Expected results

email
name

Any ideas?

+3
source share
2 answers

It worked fine on my test site.

You did not copy the getInputName method in your example. I would start looking there. Maybe you will return the desired variable?

My test code is:

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

Conclusion:

emailname

what is right.

+2
source

debugging a little bit :)

  • in the InputName echo set, enter $ inputName before assignment
  • in set inputName echo type $ this-> input_name before assignment
  • InputName $this- > _

inputName , ,

0

Source: https://habr.com/ru/post/1741229/


All Articles