Add a trait to a class as a private variable

Posted 4 weeks 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,

$this->trait->method();

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?

Thanks.

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

Reply to

Use Markdown with GitHub-flavored code blocks.