获取调用另一个方法的方法的名称


Get the name of the method that called another method

目标

获取调用另一个方法的方法的名称。

问题

我需要在另一个方法中获得一个方法名称,现在我使用的是:

$crazyDinosaur = new CrazyDinosaur(300, 600);
$crazyDinosaur->attack(new NinjaCat(), __FUNCTION__);

如果没有__FUNCTION__,我如何发现CrazyDinosaur攻击了NinjaCat?有可能吗?

更多详细信息

我想要的是:x触发一个事件。我不想再说x触发了事件,因为事件应该知道是谁在触发自己。

您通常会有一个抽象的ActorCharacter类,对它们进行子类,然后创建子类的实例。例如:

<?php
abstract class Actor {}
abstract class Animal extends Actor {}
class Dinosaur extends Animal {}

正如您所知,类可以具有属性。因此,一个属性可以是$type,它保存类的字符串表示。因此,如果您创建了Dinosaur的实例,那么$type可以简单地为dinosaur

所以现在我们有了:

<?php
abstract class Animal extends Actor
{
    protected $type;
}    
class Dinosaur extends Animal
{
    protected $type = 'dinosaur';
    public function getType()
    {
        return $this->type;
    }
}
class Cat extends Animal
{
    protected $type = 'cat';
}
$crazyDinosaur = new Dinosaur();
$crazyCat = new Cat();

我认为你的问题是你把attack()方法附加到了错误的类上;我会把它附在受害者的课堂上。所以,如果恐龙正在攻击cat,那么我会调用cat类上的attack()方法,并将您的恐龙对象作为参数传递。这样,只需检查$attacker是什么类型的类,就可以知道什么在攻击什么

<?php
class Cat extends Animal
{
    public function attack(Actor $attacker)
    {
        // code here to do things like deduct cat's health etc.
    }
}
$crazyDinosaur = new Dinosaur();
$crazyCat = new Cat();
$crazyCat->attack($crazyDinosaur);

您可以扩展attack方法以接受其他参数。例如,攻击的强度会改变它对受害者造成的伤害。

我还建议研究观察者模式,因为在这种情况下这是理想的。此外,PHP不是一种事件驱动的语言,因此也不是最适合游戏的语言。

这个怎么样

class creature{
public $attack_strength;
public $health ;
public function attack($enemy){
  $damage = $this->attack_strength;
  $enemy->health -= $damage;
  log_event($this->name . " attacked " . $enemy->name . " making " . $demage . " points of damage");
}
}
class NinjaCat extends creature{
}
class crazyDinosaur extends creature{
}

我想您正在寻找get_class($this):

...
function attack($victim)
{
  $attacker = get_class($this);
  var_dump($attacker);
}
...