Use of Trait in static method

Asked

Viewed 56 times

2

Taking the example below, how can the Trait within the method static class?

  1. Is it possible? How?
  2. Is it bad practice? What is the right way?

    trait TestTraits
    {
        public function thistraitmethod($data)
        {
           return $data;
        }
    }
    
    
    class ClassUsingTrait
    {
        use TestTraits;
    
        public static function staticmethod($data)
        {
            return $this->thistraitmethod($data);
        }
    }
    

1 answer

2


This is not possible for the simple reason that $this does not exist in this context. A static method is in the context of the class, not the instance. Which $this it will catch? Is there any? It is impossible to use any instance member within a static method. The problem is not the trait in itself, only a consequence of what he does, so applies to anything that changes context in this way.

Otherwise, instances can access static members since there is only one instance of it.

It is possible to do so:

trait TestTraits {
    public function thistraitmethod($data) {
       return $data;
    }
}

class ClassUsingTrait {
    use TestTraits;
    public static function staticmethod(ClassUsingTrait $objeto, $data) {
        return $objeto->thistraitmethod($data);
    }
}

$x = new ClassUsingTrait();
ClassUsingTrait::staticmethod($x, "xxx");

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.