0

what i want to ask is, why the $character property of Forest class is a reference instance to $character Object not the clone ?

<?php
// example code

Class Ogre
{
 protected $position = 0;

 protected $name;

 public function setPosition($position)
 {
     $this->position = $position;
 }

 public function getPosition()
 {
     return $this->name.' position is at axis '.$this->position.'.';
 }

 public function setName($name)
 {
     $this->name = $name;
 }
 public function walk($step)
 {
  $this->position += $step;
  return $this;
 }

 public function getInfo()
 {
     return 'Type: '.self::class.', Name:  '.$this->name;
 }
}

class Forest
{
    protected $character;

    public function __construct($character)
    {
        // var_dump($character);
        $character->setPosition(55);
    }

    public function getName()
    {
        return 'Theme Name : Forest';
    }
}

$character = new Ogre();
$character->setName('Magi');

echo $character->getPosition(); //the position is 0 i've never defined the position

$theme = new Forest($character);

echo $character->getPosition(); //it shows 55 because i defined it inside Forest constructor

  • Because you never explicitly `clone`d the object, and there's only one object at any one time. – deceze Jun 05 '20 at 10:59
  • @deceze so i should use the `clone` keyword inside the Forest constructor ? – Sayid Mabrur Jun 05 '20 at 11:07
  • I don't know, *should* you? Do you want two copies of your character? If so, why not *instantiate* two? – deceze Jun 05 '20 at 11:08
  • thank you for the help and the reply @deceze the post here https://stackoverflow.com/questions/1107016/are-objects-in-php-passed-by-value-or-reference makes me understand how it works – Sayid Mabrur Jun 05 '20 at 11:12

0 Answers0