1 year ago

Add a trait to a class as a private variable

Posted 1 year ago by CorCronje

Hello there!

I've got a trait that wish to use in an abstract way inside a class, my objective is to use the trait in the following manner,


I've attempted the following, but it does not work as expected,

trait NumberFormatter
    function toCurrency($float)
        return number_format($float, 5 , '.', ' ');

class Sales {

    use NumberFormatter;

    private $format;

    public function __construct()
        $this->format = NumberFormatter::class;

    public function getSalesAmount()
        return $this->format->toCurrency('123456.3210');

Is it possible to do something like this in PHP?


Please sign in or create an account to participate in this conversation.