Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
PHP Class Using Same Name as 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 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.

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?

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

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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
about 4 years ago · Santiago Trujillo Report

0

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";
    }
}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!