在方法内部调用设置方法

时间:2020-06-05 10:56:25

标签: php oop

我想问的是,为什么Forest类的$character属性是$character对象而不是克隆对象的引用实例?

<?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

0 个答案:

没有答案
相关问题