Use of Trait in static method

2

Given the example below, how can you use the Trait method inside the static method of the class?

  • Is it possible? How?
  • 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);
        }
    }
    
  • asked by anonymous 18.04.2018 / 15:45

    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. What% of% will he get? Is there any? It is impossible to use any instance member within a static method. The problem is not $this itself, just a consequence of what it does, so it's true for everything that changes context in this way.

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

    You can do this:

    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");
    
        
    18.04.2018 / 15:59