PHP Class Using Same Name as Trait Function

女生的网名这么多〃 提交于 2019-12-05 10:49:19

You can do it this way :

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

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

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

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

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();

You can only change the visibility :

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

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

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

Yes, You can do it this way also, you can use multiple function of a trait like this.

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";
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!