PHP类使用与Trait函数相同的名称

5
我有以下代码样例。

我有以下代码样例。

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

我可以列出为什么这是必要的所有细节,但我想让这个问题简单明了。由于我的特殊情况,扩展客户端类不是答案。

一个 trait 是否可以有与使用它的类相同的函数名称,但同时调用 trait 的函数和类的函数呢?

目前它只会使用类的函数(似乎覆盖了 trait 的函数)。

2个回答

15
您可以这样做:
class client{
   use sampletrait {
       hello as protected sampletrait_hello;
   }

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

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

编辑2: 刚刚对“重命名” trait 函数进行了一些研究。

如果您正在重命名一个函数但不覆盖另一个函数(参见示例),则两个函数都将存在(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

是的,如果您希望能够从外部范围调用该方法并因此保留两种方法,甚至可以将其保持为公共的。 - Alex
@AlexvanVliet 谢谢你今天教给我一些新的有用的东西。 - ceejayoz
@ceeyajoz 随时! - Alex
我尝试过这样做,但当函数被调用时没有任何反应或输出,这非常奇怪,有什么想法吗? - Joseph Astrahan
我又提了一个问题,http://stackoverflow.com/questions/43702562/use-trait-function-with-same-name-but-optionally - Joseph Astrahan
显示剩余6条评论

1

是的,你也可以这样做,你可以像这样使用一个trait的多个函数。

在这里尝试这段代码片段

<?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";
    }
}

谢谢你的示例! - Joseph Astrahan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接