PHP Class 使用与特征函数相同的名称

PHP Class Using Same Name as Trait Function

我有以下代码作为示例。

trait sampletrait{
   function hello(){
      echo "hello from trait";
   }
}

class client{
   use sampletrait;

   function hello(){
      echo "hello from class";
      //From within here, how do I call traits hello() function also?
   }
}

我可以详细说明为什么这是必要的,但我想让这个问题保持简单。由于我的特殊情况,从 class 客户端扩展不是这里的答案。

是否可以让特征与使用它的 class 具有相同的函数名称,但除了 classes 函数之外还调用特征函数?

目前它只会使用 classes 函数(因为它似乎覆盖了特征)

你可以这样做:

class client{
   use sampletrait {
       hello as protected sampletrait_hello;
   }

   function hello(){
      $this->sampletrait_hello();
      echo "hello from class";
   }
}

编辑: 糟糕,忘了 $this->(感谢 JasonBoss)

编辑 2: 刚刚对 "renaming" 特征函数做了一些研究。

如果您重命名一个函数但不覆盖另一个函数(参见示例),则两个函数都将存在 (php 7.1.4) :

trait T{
    public function f(){
        echo "T";
    }
}

class C{
    use T {
        f as public f2;
    }
}

$c = new C();
$c->f();
$c->f2();

您只能更改可见性:

trait T{
    public function f(){
        echo "T";
    }
}

class C{
    use T {
        f as protected;
    }
}

$c->f();// Won't work

是的,你也可以这样做,你可以像这样使用trait的多重功能。

Try this code snippet here

<?php
ini_set('display_errors', 1);

trait sampletrait
{
    function hello()
    {
        echo "hello from trait";
    }
}

class client
{    
    use sampletrait
    {
        sampletrait::hello as trait_hello;//alias method
    }

    function hello()
    {
        $this->trait_hello();
        echo "hello from class";
    }
}