PHP class using the same name as the trait function

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 give all the details about why this is needed, but I want this question to be simple. Extending from a class client is not an answer here due to my particular situation.

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

It will currently use the classes function (as if it overrides traits)

+3


source to share


2 answers


You can do it like this:

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

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

      

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

Edit 2: Just did some research on the "rename" functions.



If you rename a function but don't overwrite the other (see 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

      

+6


source


Yes, you can do it the same way, you can use multiple functions trait

like this.

Try this piece of code 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";
    }
}

      

+1


source







All Articles