【问题标题】:Can I define trait's variable in class?我可以在课堂上定义 trait 的变量吗?
【发布时间】:2018-04-21 07:59:51
【问题描述】:

当我调用 $article->test()->uri('test-content') 函数时,这是在 uri 变量的 trait 中显示测试内容,但在文章类中 uri 变量是返回为空。如何使用此调用定义 uri 变量?

特征/Query.php:

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

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

内容/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;
    }

【问题讨论】:

    标签: php traits


    【解决方案1】:

    当你这样做时

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

    它首先调用$article->test()。所以你还没有调用Query::uri() 来填写$uri 变量。你需要反转它:

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

    【讨论】:

      猜你喜欢
      • 2020-03-21
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      相关资源
      最近更新 更多