Daniel Pereira
Daniel Pereira

Reputation: 495

Error calling a interface method in php

Hey guys i have this sample code and i want to call the method like this code:

<?php
interface Item{
    function getRes();
}

class Weapon implements Item{
    public function getRes(){
        echo "Res";
    }
}

abstract class Player implements Item{
     public function defend(){
           $this->Item->Weapon->getRes();
     }
}
?>

I know this doesn't work but how is the best way to do this call.

Upvotes: 1

Views: 137

Answers (1)

WNP
WNP

Reputation: 161

If you are inheriting the Item class in player (which I don't think a player is a type of item ;) ), you would need to implement the getRes function.

Moving away from that, you will most likely want to rely on dependency injection (DI) in order for your player to get a weapon.

interface Item {
  function getResponse();
}

interface AttackItem extends Item {
}

interface DefenseItem extends Item {
}

class Sword implements AttackItem {
  public function getResponse(){
    return "Swing of the sword!";
  }
}

class Shield implements DefenseItem {
  public function getResponse(){
    return "Defend with the shield!";
  }
}

class Player {
  public function __construct(AttackItem $attackItem, DefenseItem $defenseItem) {
    $this->attackItem = $attackItem;
    $this->defenseItem = $defenseItem;
  }

  public function attack(){
    return $this->attackItem->getResponse();
  }
  public function defend(){
    return $this->defenseItem->getResponse();
  }
}

$player = new Player(new Sword(), new Shield());

echo $player->attack() . "\n";
echo $player->defend() . "\n";

Upvotes: 2

Related Questions