fedev
fedev

Reputation: 416

Can I define trait's variable in class?

When I call $article->test()->uri('test-content') function, this is show test-content in trait for uri variable but in article class uri variable is return as null. How can I define uri variable with this call?

Traits/Query.php:

trait Query
{
    protected $uri;
    protected $v = 'v1';

    public function uri($uri)
    {
        $this->uri = $uri;
        return $this;
    }

Content/Article.php

class Article extends Api 
{
    use Query;

    public $content;

    public function __construct() {
        parent::__construct();
    }

    public function test() {
        $this->content = $this->v . ' - ' . $this->uri;
        return $this;
    }

Upvotes: 1

Views: 64

Answers (1)

Barmar
Barmar

Reputation: 780899

When you do

$article->test()->uri('test-content');

it's calling $article->test() first. So you haven't called Query::uri() yet to fill in the $uri variable. You need to reverse it:

$article->uri('test-content')->test();

Upvotes: 3

Related Questions