PHP类使用与Trait函数相同的名称 [英] PHP Class Using Same Name as Trait Function

查看:379
本文介绍了PHP类使用与Trait函数相同的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码作为示例.

I have the following code as a sample.

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

我可以详细说明为什么这样做是必要的,但我想使这个问题保持简单.由于我的特殊情况,从班级客户那里扩展并不是解决问题的方法.

I could put all the details as to why this is necessary but I want to keep this question simple. Extending from the class client is not the answer here due to my particular situation.

是否可以使trait与使用它的类具有相同的函数名称,但是除了classes函数之外,还要调用traits函数?

Is it possible to have a trait have the same function name as the class using it, but call the traits function in addition to the classes function?

当前它将仅使用classes函数(因为它似乎覆盖了特征)

Currently it will only use the classes function (as it seems to override the traits)

推荐答案

您可以这样操作:

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

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

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

Edit : Whops, forgot $this-> (thanks JasonBoss)

刚刚对重命名"特征功能进行了一些研究.

Edit 2 : Just did some research on "renaming" trait functions.

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

If you are renaming a function but not overwriting another one (see the example), both functions will exist (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

这篇关于PHP类使用与Trait函数相同的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆