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

时间:2017-04-30 02:28:26

标签: php class traits php-7 php-traits

我将以下代码作为样本。

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

我可以把所有细节都说明为什么这是必要的,但我想让这个问题变得简单。由于我的特殊情况,从班级客户端延伸不是答案。

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

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

2 个答案:

答案 0 :(得分:10)

你可以这样做:

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

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

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

编辑: 哎呀,忘了$ this-> (感谢JasonBoss)

编辑2: 刚做了一些关于“重命名”特质功能的研究。

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

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

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

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

您只能更改公开程度:

{{1}}

答案 1 :(得分:1)

是的,你也可以这样做,你可以像这样使用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";
    }
}
相关问题